重置计数器后setInterval执行速率异常加快的原因排查
计数器重置后再次启动速率加快的原因及解决方法
问题描述
首次运行计数器时,秒数按1000毫秒的正常间隔递增;但将计数器重置为0后再次启动,发现计数速率明显加快。明明setInterval的间隔设置为固定的1000毫秒,这一现象不符合预期,请问是什么原因导致的?
原代码
JavaScript 代码
function StartCounter() { setInterval(IncreaseSeconds, 1000); } function IncreaseSeconds() { let seconds = parseInt(document.getElementById("setter-post-counter").innerText); document.getElementById("setter-post-counter").innerText = seconds + 1; } function Reset() { document.getElementById("setter-post-counter").innerText = 0; }
HTML 代码
<div class="onerow"> <p id="setter-post-counter">0</p><span>seconds</span></div> <button onClick="StartCounter()">Start</button> <button onClick="Reset()">Reset</button>
原因分析
问题出在StartCounter()函数的实现上:每次点击Start按钮时,都会调用setInterval创建一个新的定时器,而之前创建的定时器并没有被清除。这些定时器会同时独立运行,每一个都会每秒触发一次IncreaseSeconds函数。
比如:
- 第一次点击Start,1个定时器工作,每秒秒数+1
- 重置后再次点击Start,就会有2个定时器同时触发,每秒秒数+2,看起来速率翻倍
- 多次点击Start的话,定时器数量会越来越多,计数速率会越来越快
解决方法
我们需要用一个变量保存定时器的ID,每次启动新定时器前先清除旧的,避免多个定时器同时运行。
修改后的代码
JavaScript 代码
// 全局变量存储定时器ID let counterTimer = null; function StartCounter() { // 先清除之前的定时器,避免重复创建 if (counterTimer) { clearInterval(counterTimer); } // 创建新的定时器并保存ID counterTimer = setInterval(IncreaseSeconds, 1000); } function IncreaseSeconds() { let seconds = parseInt(document.getElementById("setter-post-counter").innerText); document.getElementById("setter-post-counter").innerText = seconds + 1; } function Reset() { // 重置秒数 document.getElementById("setter-post-counter").innerText = 0; // 可选:如果重置时需要停止计数,就清除定时器 // if (counterTimer) { // clearInterval(counterTimer); // counterTimer = null; // } }
HTML 代码(无需修改)
<div class="onerow"> <p id="setter-post-counter">0</p><span>seconds</span></div> <button onClick="StartCounter()">Start</button> <button onClick="Reset()">Reset</button>
这样修改后,每次点击Start按钮都会先清除之前的定时器,再创建新的,就不会出现多个定时器同时运行导致计数速率加快的问题了。
内容的提问来源于stack exchange,提问作者Kate
相关产品推荐
相关产品推荐

