运行其他功能时,jQuery停止倒计时

时间:2018-09-27 15:40:49

标签: jquery

我正在尝试制作一个运行功能的倒数计时器,但是还可以通过按下按钮来手动设置倒计时:

计时器工作正常:

HTML

<button class="countdown" onclick="refresh()">•</button>

JS

 // COUNTDOWN TIMER
 $(function() {
   var start = "1:00";
   var interval = setInterval(function() {
     var timer = start.split(':');
     var minutes = parseInt(timer[0], 10);
     var seconds = parseInt(timer[1], 10);
     --seconds;
     minutes = (seconds < 0) ? --minutes : minutes;
     if (minutes < 0) {
       clearInterval(interval);
       refresh();
     } else {
       seconds = (seconds < 0) ? 59 : seconds;
       seconds = (seconds < 10) ? '0' + seconds : seconds;
       $('.countdown').html(minutes + ':' + seconds);
       start = minutes + ':' + seconds;
     }
   }, 1000);
 });

// MY REFRESH FUNCTION
function refresh() {
   alert("Alert");
   $('.countdown').html("Loading");
 }

我正在苦苦挣扎的是,当我单击手动覆盖按钮以运行刷新功能时,计时器仍然继续倒计时(例如,装入已由倒数计时器代替)。单击按钮应该做的是停止倒计时功能的运行。

任何人都可以帮助我该怎么做吗?

1 个答案:

答案 0 :(得分:1)

var interval = null;

// COUNTDOWN TIMER
$(function() {
  var start = "1:00";
  interval = setInterval(function() {
  var timer = start.split(':');
    var minutes = parseInt(timer[0], 10);
    var seconds = parseInt(timer[1], 10);
    --seconds;
    minutes = (seconds < 0) ? --minutes : minutes;
    if (minutes < 0) {
       clearInterval(interval);
       refresh();
    } else {
       seconds = (seconds < 0) ? 59 : seconds;
       seconds = (seconds < 10) ? '0' + seconds : seconds;
       $('.countdown').html(minutes + ':' + seconds);
       start = minutes + ':' + seconds;
    }
  }, 1000);
});

// MY REFRESH FUNCTION
function refresh() {
  alert("Alert");
  $('.countdown').html("Loading");
}

$('.countdown').click(function() {
  clearInterval(interval);
});