You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JS中实现按住F键时执行setInterval、松开时停止?

问题分析

你的代码问题在于:按住F键时,浏览器会连续触发keydown事件,每次触发都会创建一个新的setInterval定时器,但process变量只会保存最后一个定时器的ID。当你松开F键时,clearInterval只能清除最后那个定时器,之前创建的定时器还在后台运行,导致函数持续执行。

修复方案

在keydown事件中先检查是否已有定时器存在,只有当定时器未创建时才初始化它;同时确保keyup时正确清除定时器:

let process = null;

function func() {
    console.log('just for example');
}

window.addEventListener("keydown", (e) => {
    // 仅当定时器未存在时才创建新的
    if (e.key === "f" && !process) {
        process = setInterval(func, 100);
    }
});

window.addEventListener("keyup", (e) => {
    if (e.key === "f" && process) {
        clearInterval(process);
        process = null;
    }
});
额外优化(可选)

如果需要更精准地避免重复触发的干扰,可以利用e.repeat属性判断是否是重复触发的keydown事件,只在第一次按下时创建定时器:

let process = null;

function func() {
    console.log('just for example');
}

window.addEventListener("keydown", (e) => {
    // 仅在首次按下F键且无定时器时创建
    if (e.key === "f" && !e.repeat && !process) {
        process = setInterval(func, 100);
    }
});

window.addEventListener("keyup", (e) => {
    if (e.key === "f" && process) {
        clearInterval(process);
        process = null;
    }
});

内容的提问来源于stack exchange,提问作者Beluker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 10:03:11