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

启动新setInterval前清除旧实例:汉诺塔游戏计时器重置问题

解决汉诺塔拖拽时计时器重叠的问题

当前问题的核心是:每次拖拽调用timer()时都会新建一个定时器,旧定时器未被清除,导致多个定时器同时修改倒计时数值,出现计数重叠、乱跳的现象。

修改后的代码实现

计时器函数(修复重叠问题)

// 将计时器变量放在全局作用域,保留跨调用的引用
let downloadTimer;

function timer() {
    // 先清除已存在的旧计时器,避免重叠运行
    if (downloadTimer) {
        clearInterval(downloadTimer);
    }
    let timeleft = 10;
    downloadTimer = setInterval(function () {
        if (timeleft <= 0) {
            clearInterval(downloadTimer);
            alert("Game over! You ran out of time\nPlay again?");
            location.reload();
        } else {
            timeleft -= 1;
            document.getElementById("timer").innerHTML = timeleft;
        }
    }, 1000);
}

拖拽调用代码(无需改动调用逻辑)

function Drag() {
    $(".draggable").draggable({
        stack: $(".draggable"),
        helper: "clone",
        start: function () {
            timer(); // 每次拖拽开始时重置计时器
            var parentNode = "#" + this.parentNode.id;
            platforms.push(parentNode);
            var shape = "#" + this.id;
            sequence.push(shape);
            var shapeParent = this.closest(".holder").id;
            shapeParent = "#" + shapeParent;
        },
    });
}

关键改动说明

  • 将downloadTimer变量移到timer()函数外部,使其在多次函数调用间保持引用,不会每次调用都重新声明新变量
  • 在timer()函数开头添加判断逻辑:如果已有计时器在运行,先清除旧计时器,再创建新的计时器
  • 修正了弹窗提示的换行格式,添加\n保证提示文字正常换行显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:32:02