使用setInterval暂停并继续

pause and continue using setInterval

本文关键字:继续 暂停 setInterval 使用      更新时间:2023-09-26

我想要实现的是当您单击此href <a href="javascript:void(0)" class="pauser">pause/continue</a>时,计时器暂停并在再次按下时继续。

<script>
$(document).ready(function () {
    var counter = 10;
    var id = setInterval(function() {
       counter--;
       if(counter > 0) {
            var msg = 'You can continue ' + counter + ' seconds';
            $('#notice').text(msg);
       } else {
            $('#notice').hide();
            $('#download').show();
            clearInterval(id);
      }
    }, 1000);
});
</script>

与jQuery相关的HTML在这里,如果你需要。

<a href="http://myurl.com" id="download" class="button" style="display: none;font-size:30px;">Continue !!</a><p id="notice">
You can continue in 10 seconds</p>

我会让你的pause事件设置一个布尔值,然后在递减计数器之前检查这个布尔值:

<a href="javascript:setPause();" class="pauser">pause/continue</a>

var ispaused=false;
function setPause(){
   ispaused=!ispaused;
}

$(document).ready(function () {
var counter = 10;
var id = setInterval(function() {
   if(!ispaused){ ////the only new line I added from your example above
     counter--;
     if(counter > 0) {
          var msg = 'You can continue ' + counter + ' seconds';
          $('#notice').text(msg);
     } else {
          $('#notice').hide();
          $('#download').show();
          clearInterval(id);
    }
  }
}, 1000);
});

应该可以了,对吧?