javascript - 暂停并继续使用 setInterval

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

如果您需要,我的与 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>

最佳答案

好吧,我会让你的暂停事件设置一个 bool 值,然后在你递减计数器之前检查这个 bool 值:

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

应该可以吧?

关于javascript - 暂停并继续使用 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8159191/

相关文章:

javascript - 使用 Highcharts 按 ID 选择点

javascript - 在 Html 中获取以前的 Span

html - html 元素和 div 之间的空白

PHP 发票引用 ID 自动递增

javascript - 根据第一个下拉列表的选定值填充第二个下拉列表

javascript - 数学随机在数组中查找名称而不重复

jquery - 如何在 Spring MVC 中使用 AJAX 渲染 View

javascript - 获取元素 eq() 索引

javascript - 如何使用jquery在表中添加列?

javascript - 复制 URL 参数并粘贴到 HTML 上