2015-08-30 223 views
0

我正在尝试创建一个番茄钟(一个倒计时25分钟的生产力和5分钟的休息时间倒计时),并且我无法停止休息时间倒计时。如何在第二次倒计时后停止Javascript计时器?

这里的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); 
}); 

这里是我的codepen:http://codepen.io/cenjennifer/pen/pjzBVy?editors=101

FYI:我的时间缩短,这样我可以很容易地测试功能。

+0

你看过clearTimeout(id)吗? –

回答

2

变化:

clearInterval(this.countdown); 

到:

clearInterval(countdown); 

不需要this关键字作为countdown变量是breakClock()功能的父范围的局部变量。

+0

你说这不是_needed_,也许你应该更严格一点,这是错的吗? – Jonast92

+0

我实际上尝试使用clearInterval(倒计时)最初,它并没有工作。 – PBandJen