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

JavaScript中clearInterval不生效,元素移动无法停止如何解决?

问题原因
  • 作用域错误:在runner_go函数内定义的const go是局部变量,仅在该函数内部可访问,move_left调用clearInterval(go)时会直接抛出变量未定义的错误,定时器根本无法被清除。
  • 判断逻辑时序错误:代码先修改了元素的left值,再用修改前的位置做阈值判断,就算作用域没有问题,阈值触发也会晚一步。
  • 额外隐患:mouseover事件会在鼠标每次移入body的子元素时重复触发,会创建多个并行定时器,导致元素移动速度越来越快。
修复代码

直接替换原有script标签内容即可,也可以使用下方完整代码:

<script>
// 全局存储定时器ID,保证两个函数都能访问
let go = null;
function runner_go()
{
    // 已有定时器运行时直接返回,避免重复创建
    if(go !== null) return;
    const load_time = performance.now();
    go = setInterval(move_left,20);
}

function move_left()
{
    const runner = document.getElementById('runner');
    runner.style.visibility = "visible";
    const runner_position = parseInt(getComputedStyle(runner).getPropertyValue('left'), 10);
    // 到达阈值直接清除定时器
    if (runner_position >= 2000) {
        clearInterval(go);
        go = null;
        return;
    }
    runner.style.left = runner_position + 17 + "px";
}
</script> 
</head> 
<body style="background-color:gray;" onmouseover = "runner_go();">
    <div>
       <h1>Running!</h1>
    </div>
    <img src="images/runner_l.png" alt ="running man" style="position:relative; visibility:hidden;" id = "runner"/> 
</body>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:54:05