在jQuery中创建函数循环

时间:2018-09-27 15:59:28

标签: jquery

我有此代码,可以正常工作。当倒数计数为0时,它将调用刷新功能。但是,刷新功能完成后,我希望倒数计时器再次从1:00开始。我无法调用倒数计时器函数,因为它位于主要的onload函数中。将另一个函数放在$(function() { }内并调用该函数是正确的解决方案吗?

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) {
      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() {
  clearInterval(interval);
  $('.countdown').html("Refreshing");
}

1 个答案:

答案 0 :(得分:1)

只需命名整个例程即可,您可以随意调用它:

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

$(function() {
  runCountdown();
});
.countdown {
  font-size: 3rem;
  display: flex;
  justify-content: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="countdown"></div>

与从函数中调用refresh()的方式相同,您可以从刷新中调用另一个函数。只要您给它一个参考。一个名字。