I need to execute a setInterval
function only when a specific key (F in this case) is being pressed, and then clear it when the key is not pressed.
So far, I have tried this:
var process;
function func(){
console.log('just for example');
}
window.addEventListener("keydown", (e)=>{
if(e.key === "f") process = setInterval(func, 100);
});
window.addEventListener("keyup", (e)=>{
if(e.key === "f") clearInterval(process), process = null;
});
But when I release the F key, the function keeps on executing.
Any help is very much appreciated!
3
Answers
Use
??=
to set the interval only once:You can remove the
keydown
event listener when the key is pressed, and then add it again when the key is released. As was already mentioned in the comments, this technique will prevent the creation of multiple interval timers due to repeatedkeydown
events being fired for a single held key.Using
??=
or clearing the interval is perfectly fine and elegant, but if the user releases the "f" key fast enough, the function won’t be called because the interval will be cleared.Instead, you might consider doing this with
setTimeout
instead ofsetInterval
. With the following code example, when the user presses the "f" key, even if they let it go within 100 milliseconds, the function will still execute.A quick explanation of the code is that when the user presses "f", a
setTimeout
is initialized that will call the function. If the "f" key is still pressed when the function is called, the timeout is reset.