启动新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
相关产品推荐
相关产品推荐

