【问题标题】:Implement countdowning of the second timer after first timer completed在第一个定时器完成后实现第二个定时器的倒计时
【发布时间】:2017-01-18 06:56:13
【问题描述】:

我是一名尝试创建番茄钟项目的编程初学者,并希望在会话倒计时完成后触发中断倒计时。如图所示。

计时器是通过输入字段设置的,根据想法中断计时器应该倒计时设置值,实际上它倒计时会话的值。


Javascript 代码

function sessionTimer(seconds) {
  clearInterval(countdown);
  const t = new Date();
  const end = t.getTime() + seconds * 1000;
  displayTimerLeftSession(seconds);
  console.log({
    t,
    end
  });

  countdown = setInterval(() => {
    if (!isPaused) {
      const remainSeconds = Math.round((end - t.getTime()) / 1000);
      if (remainSeconds < 0) {
        clearInterval(countdown);
        breakTimer(seconds);
        return;
      }
      displayTimerLeftSession(remainSeconds);
      t.setSeconds(t.getSeconds() + 1);
    }
  }, 1000);
  t.setSeconds(t.getSeconds() + 1) - 1;
}

我知道是什么问题。因为我在 sessionTimer 函数中调用了 breakTimer,但是我不知道如何在会话后进行中断计时器倒计时。我的代码很草率,无论如何都需要重构。请不要严厉评价我。想看代码请参考the Project

【问题讨论】:

    标签: javascript timer


    【解决方案1】:

    希望我正确地解释了您的问题。您可以做的一件事是在计时器完成后触发回调。在n 秒过去后,您清除间隔并触发指示计时器已完成的回调。

    function timer(seconds, callback) {
      var countDown = function() {
        console.log(seconds);
        if (seconds-- == 0) {
          clearInterval(time);
          callback()
        }
      };
      
      countDown();
      var time = setInterval(countDown, 1000);
    }
    
    console.log('Starting session timer...');
    timer(5, function() {
      console.log('Session timer complete. Starting break timer...');
      timer(5, function() {
        console.log('Break timer complete.');
      });
    });

    【讨论】:

      【解决方案2】:

      我已经创建了 breakSeconds 全局变量并在提交时在函数中更新它

      document.customFormBreak.addEventListener('submit', function(e) {
        e.preventDefault();
        breakSeconds = this.minutesBreak.value * 60;
        displayTimerLeftBreak(breakSeconds);
        this.reset();
      });
      

      如果您想查看代码,请转到project

      【讨论】:

        猜你喜欢
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 2014-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-17
        相关资源
        最近更新 更多