简体   繁体   中英

Detecting duration of key-press using JavaScript

I'm very new to JavaScript, sorry if this is a dumb question, I haven't been able to find a good answer online.

I'm currently using:

document.body.addEventListener("keydown", function(e) { keys[e.keyCode] = true; });
document.body.addEventListener("keyup", function(e) { keys[e.keyCode] = false; });

to detect user input, which works quite well for my purpose, but I can't think of a good way to figure out how long a key has been pressed down.

I've tried putting a while-loop that exits if keys[index] returns false and increments a counter in the loop, but that just seems to break the script. I'm guessing I could write a function that specifically detects if the key I want has been released, but I'm not sure how to go about that properly.

Additionally, I only need to check it for one key.

Instead of setting boolean values, set a timestamp on keydown, then retrieve it and compare against the current timestamp on keyup:

 const signalKeypressDuration = (key, duration) => { console.log(`Key ${key} pressed for ${duration} ms`); }; const keys = {}; document.body.addEventListener("keydown", ({ key }) => { if (!keys[key]) keys[key] = Date.now(); }); document.body.addEventListener("keyup", ({ key }) => { signalKeypressDuration(key, Date.now() - keys[key]); keys[key] = null; });

Instead of putting in true in keydown , put new Date() . Instead of putting in false in keyup , calculate new Date() - keys[e.keyCode] and store it somewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM