How to detect whether if a key is being pressed down?


2021 EDIT: For newer versions of PsychoPy, please use the Python code provided here for offline experiments: Failure to detect pressed key - #8 by sol


After looking at the generated .js files and the source code of the PsychoJS library, I figured out how to do this.

All code is javascript.

begin experiment

m_rot_kb = new core.Keyboard({psychoJS: psychoJS, clock: new util.Clock(), waitForStart: true});
key_list = [];
key_name = "";

begin routine

m_rot_kb.clock.reset();
m_rot_kb.start();
m_rot_kb.clearEvents();

each frame:

let keys_obj = m_rot_kb.getKeys({keyList: ["left", "right"], waitRelease: false, clear: false});

key_list = key_list.concat(keys_obj);
if (key_list.length > 0) 
{
    key_name = key_list[key_list.length - 1].name;
    key_duration = key_list[key_list.length - 1].duration;
    //console.log(key_name);
    //console.log(key_duration);
    if(key_name === "right" && key_duration == undefined)
    {
         console.log("right");
    }
    else if(key_name === "left" && key_duration == undefined)
    {
         console.log("left");
    }
}

end routine

m_rot_kb.clock.reset();
m_rot_kb.stop();
m_rot_kb.clearEvents();
2 Likes