暂停并继续使用setInterval

时间:2011-11-16 21:46:34

标签: javascript jquery html

我想要实现的是当您单击此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>

如果需要,我的HTML与jQuery相关。

<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>

1 个答案:

答案 0 :(得分:7)

好吧,我只是让你的暂停事件设置一个布尔值,然后在递减计数器之前检查该布尔值:

<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);
});

应该这样做,对吧?

相关问题