我需要仅在按下特定键(本例中为“F”)时执行 setInterval 函数,然后在未按下该键时清除它。
我试过这个:
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;
});
但是当我释放F键时,该函数继续执行。非常感谢任何帮助:D
使用
??=
仅设置一次间隔:
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;
});