单击暂停按钮后,计时器显示为停止,但当我单击恢复时,我发现计数器继续在幕后倒计时。我想 setInterval 有问题。请帮我。我在 CodePen 上的项目如果需要,供引用。
我的定时器功能
function timer(seconds) {
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimerLeft(seconds);
console.log({
now,
then
});
countdown = setInterval(() => {
if (!isPaused) {
const remainSeconds = Math.round((then - Date.now()) / 1000);
if (remainSeconds < 0) {
clearInterval(countdown);
return;
}
displayTimerLeft(remainSeconds);
}
}, 1000);
}
暂停和开始点击事件
pause.addEventListener('click', function() {
isPaused = true;
return;
})
start.addEventListener('click', function() {
isPaused = false;
})
最佳答案
看看你的代码,我想问题是你保持相同的 then
值,这最终是计时器应该结束的时间戳。现在,您不是暂停倒计时,而是停止显示更改。
我建议改用您的变量 seconds
(并使用模 % 计算显示),并每秒递减一次。这样,暂停显示将有效地暂停减少。
关于javascript - 单击暂停按钮后计时器实际上并未停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41572879/