如何在第二次倒计时后停止Javascript计时器

How to stop a Javascript Timer after the second countdown?

本文关键字:Javascript 计时器 倒计时 第二次      更新时间:2023-09-26

我正在尝试创建一个番茄钟(一个25分钟的工作倒计时和5分钟的休息时间倒计时),我很难停止休息时间的倒计时。

这是我到目前为止的Javascript:

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    var countdown = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);
        seconds = seconds < 10 ? "0" + seconds : seconds;
        display.textContent = minutes + ":" + seconds;
        if (--timer < 0) {
            clearInterval(countdown);
            var breakClock = function() {
                 $("#title").text(function(i, text){
       return text === 'Breaktime' ? 'Productive Countdown' : 'Breaktime'
            }); 
             var fiveMinutes = 60 * .05,
                  display = document.querySelector('#time');
             startTimer(fiveMinutes, display);
             if (--timer < 0) {
                  clearInterval(this.countdown);
             }
            };
          breakClock();  
          }
    }, 500);
}                  
$(".startClock").click(function(){
    var twentyfiveMinutes = 60 * .25,
        display = document.querySelector('#time');
    startTimer(twentyfiveMinutes, display);
});

这是我的合作伙伴:http://codepen.io/cenjennifer/pen/pjzBVy?editors=101

仅供参考:我减少了时间,以便我可以轻松地测试功能。

change:

clearInterval(this.countdown);

:

clearInterval(countdown);

this关键字不需要,因为countdown变量是breakClock()函数父作用域的局部变量。