admin管理员组文章数量:1432759
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.
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.
Share Improve this question asked Mar 19, 2020 at 3:31 nullclinenullcline 3522 silver badges16 bronze badges 2- 1 Do you need to know how long it has been pressed before you release the key? – Alfredo Awesome Monazite Commented Mar 19, 2020 at 3:35
-
check
Date.now()
at keydown and at keyup – jsotola Commented Mar 19, 2020 at 3:38
2 Answers
Reset to default 9Instead of setting boolean values, set a timestamp on keydown, then retrieve it and pare 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.
本文标签: user inputDetecting duration of keypress using JavaScriptStack Overflow
版权声明:本文标题:user input - Detecting duration of key-press using JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745567981a2663875.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论