【发布时间】:2017-01-10 15:52:29
【问题描述】:
单击暂停按钮后,计时器的显示好像有点停止,但是当我单击恢复时,我发现计数器在场景后面继续倒计时。我猜 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' 作为你的常量。 'then' 是 js 中的一个关键字,用在 'if then' 语句中。当 js 对某个项目提出问题时,它通常会跳过函数的其余部分,因此更改变量名可能会解决它。虽然,你也应该在使用 clearInterval(variable) 时使用'variable = undefined',否则它不会一直杀死它。
-
@bobjoe 实际上不是重复的,问题在于他没有使用变量来倒数秒,而是即使在暂停时也保持结束时间戳不变。他的代码 sn-p 与您链接的帖子中的答案几乎完全相同。
标签: javascript