【问题标题】:Timer does not actually stop after pause button is clicked单击暂停按钮后计时器实际上并未停止
【发布时间】: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


【解决方案1】:

查看您的代码,我想问题是您保持相同的then 值,这最终是计时器应该结束的时间戳。现在,不是暂停倒计时,而是停止显示变化。

我建议改用您的变量 seconds(并使用模 % 计算显示),并每秒减少一次。这样,暂停显示将有效地暂停递减。

【讨论】:

    【解决方案2】:

    保留当前时间的参考,并在每个刻度处手动添加一秒。

    function timer(seconds) {
      clearInterval(countdown);
      const t = new Date();
      const end = t.getTime() + seconds * 1000;
      displayTimerLeft(seconds);
      console.log({
        t,
        end
      });
      countdown = setInterval(() => {
        if (!isPaused) {
          const remainSeconds = Math.round((end - t.getTime()) / 1000);
          if (remainSeconds < 0) {
            clearInterval(countdown);
            return;
          }
          displayTimerLeft(remainSeconds);
          t.setSeconds(t.getSeconds() + 1);
        }
      }, 1000);
    }
    

    演示:http://codepen.io/miguelmota/pen/wgMzXY

    【讨论】:

      【解决方案3】:

      setInterval 返回一个唯一的 id,可用于使用clearInterval 停止计时器:

      var id = setInterval(function(){
      console.log('running every 300 ms');
      },300);
      
      clearInterval(id) // stop timer
      

      【讨论】:

      • 这可以工作,但是需要额外的代码来恢复取消暂停的间隔。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多