How can I save keypress duration in online experiments?

Description of the problem: Hello, I want to get the time space bar was pressed. How can I do it in Builder so that it is compatible with Pavlovia as well?

Thansk in advance.

Do you want the routine to end when the space bar is released?

It would be quite easy to add a code component to do this. Off the top of my head something like:

Begin Routine

spacePressed=0

Each Frame

keys = event.getKeys()

if len(keys):
     if "space" in keys and spacePressed = 0:
          spacePressed = t
elif spacePressed > 0:
     rt = round((t-spacePressed)*1000)
     thisExp.addData('SpaceDur',rt)
     continueRoutine=False

Make sure you add a code_JS component as per my crib sheet.

Best wishes,

Wakefield

Thank you very much for the crib sheet it’s extremely helpful! :slight_smile:

Also thanks for the suggestion. Yes, I want the routine to end when the space bar is released. Shouldn’t I add waitRelease = True somewhere in my code though?

@pinar, yes you can use the waitRelease parameter in PsychoJS. So alternative method to Wakefields response which should work, where kb is your keyboard (which will need to be created using code):

let theseKeys = kb.getKeys({keyList: ['space'], waitRelease: true});
if (theseKeys.length > 0) {
  kb.keys = theseKeys[0].name;  // just the first key pressed
  kb.rt = theseKeys[0].rt;
  // a response ends the routine
  continueRoutine = false;
}

Will that record the length of time that the space bar has been pressed, or just the time at which it was released?

waitRelease isn’t needed for my method because the keyboard will be checked each frame.

Edit: Just to note that my code will fail if they press and hold down a second key after having pressed the space bar but before they release it. It waits for the first moment that no keys are down after space has first been pressed.

It looks like the duration is given:

https://www.psychopy.org/api/hardware/keyboard.html#psychopy.hardware.keyboard.Keyboard.getKeys