Reputation: 350
I know there's Detecting duration of key-press using JavaScript but I don't want to know how to detect duration after user let go of the key but while it is still held down, as Alfredo Awesome Monazite asked in a comment below the mentioned question.
So the question is:
When the user presses and holds a key, how do I detect if it has been held down for e.g. one seconds continuously and reacting to that while the key is still kept down?
Upvotes: 0
Views: 436
Reputation: 36
let repeat = false;
addEventListener("keydown", () => (repeat = true));
addEventListener("keyup", () => (repeat = false));
setInterval(() => {
if (repeat) {
//increment timer here
//console log is just an example
console.log("awd");
}
}, 100);
What you can do is set repeat to true on keydown and false on keyup by using event listeners and then increment your counter(in this case the counter being the number of times "awd" is being logged) every X miliseconds (in this case 100) if repeat is true (which it is while a key is being pushed). For higher precision lower the interval.
Upvotes: 1