反复点击开始/重置按钮引发秒表计时异常问题
问题分析与解决
问题现象
点击start按钮后计时启动,start按钮隐藏并显示pause、reset按钮;但反复点击start和reset按钮后,计时出现错误,且pause、reset按钮失效。
问题根源
每次点击start都会直接调用count(),而count()内部通过setTimeout持续创建新定时器。变量t仅保存最后一个定时器ID,之前启动的定时器未被清除,仍在后台执行,导致计数逻辑混乱;reset和pause只能清除最后一个定时器,无法终止旧的定时任务,最终引发计时错误和按钮状态失效。
修复方案
新增一个状态变量标记当前是否处于计时状态,避免重复启动定时器;同时在暂停、重置时同步更新状态。
修改后的完整代码
HTML
<h1>Stopwatch</h1> <span id="count">0</span><br /> <button id="startb" onClick="start()">Start</button> <button id="pauseb" onClick="pause()">Pause</button> <button id="resetb" onClick="reset()">Reset</button> <button id="lapb" onClick="lap()">Lap</button>
CSS
* { margin: 0; padding: 0; font-family: Arial; } body { background-color: #333; color: black; } button { width: 100px; height: 30px; line-height: 30px; text-align: center; color: #000; background-color: #c3c3c3; border: 1px solid #000; } #count { font-size: 175px; } #startb { background-color: #800080; border-color: #220022; color: #2e002e; } #pauseb { display: none; background-color: black; color: #b6b6b6; } #resetb { display: none; background-color: red; color: #3b0000; border-color: #3b0000; font-weight: bold; } #lapb { display: none; background-color: #008800; color: black; border-color: darkgreen; font-weight: bold; }
JavaScript
var c = 0; var t; var isRunning = false; // 新增状态变量,标记是否正在计时 function count() { document.getElementById("count").innerHTML = c; c = c + 1; t = setTimeout(count, 1000); } function start() { if (isRunning) return; // 如果已经在计时,直接返回,避免重复启动 isRunning = true; count(); document.getElementById("startb").style.display = "none"; document.getElementById("pauseb").style.display = "inline"; } function pause() { clearTimeout(t); isRunning = false; // 更新状态为未计时 document.getElementById("startb").style.display = "inline"; document.getElementById("pauseb").style.display = "none"; document.getElementById("startb").innerHTML = "Resume"; document.getElementById("resetb").style.display = "inline"; } function reset() { c = 0; clearTimeout(t); isRunning = false; // 更新状态为未计时 document.getElementById("count").innerHTML = c; document.getElementById("startb").style.display = "inline"; document.getElementById("startb").innerHTML = "Start"; document.getElementById("pauseb").style.display = "none"; document.getElementById("resetb").style.display = "none"; }
说明
- 新增的
isRunning变量确保同一时间只有一个定时器在运行,避免重复调用count()导致的多实例问题 - 在
start函数中先判断状态,若已在计时则直接返回,阻止重复启动 pause和reset函数中同步更新isRunning状态,保证后续操作的正确性
内容的提问来源于stack exchange,提问作者TopD0774r
相关产品推荐
相关产品推荐

