使用倒数计时器单击暂停setInterval

时间:2016-08-13 11:38:11

标签: jquery setinterval countdown

我有一个按钮,可以在点击时触发倒数计时器。我想在单击计时器框时暂停此计时器,并在再次单击时取消暂停。我能够停止点击倒计时,但我无法弄清楚如何重新开始。



jQuery(function ($) {

  var countdown;
  
  function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    countdown = setInterval(function () {
      minutes = parseInt(timer / 60, 10);
      seconds = parseInt(timer % 60, 10);

      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;

      display.text(minutes + ":" + seconds);

      if (--timer < 0) {
        clearInterval(countdown);
      }
    }, 1000);
  }
  
    $('.start-timer').on('click',function() {
      $('body').append("<div id='countdown-timer'></div>");
      var fiveMinutes = 60 * 5;
      var display = $('#countdown-timer');
      startTimer(fiveMinutes, display);
  });
  
    // Want this function to be toggling the timer countdown

  $('body').on('click', '#countdown-timer',function(){
    clearInterval(countdown);
    countdown = null;
  });
  
});
&#13;
#countdown-timer {
  position: absolute;
  top: 20%;
  cursor: pointer;
  background: rgba(0,0,0,0.4);
  color: white;
  border-width: 1px;
  border-color: #fed136; 
  font-size: 50px;
  border-radius: 4px;
}
&#13;
<body>
  <div id="countdown-timer"></div>
 <button class="start-timer">Start timer</button>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
&#13;
&#13;
&#13;

这里是小提琴:https://jsfiddle.net/wLnmk5dx/3/

0 个答案:

没有答案