最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - pause and continue using setInterval - Stack Overflow

programmeradmin7浏览0评论

what i want to achieve is when you click this href <a href="javascript:void(0)" class="pauser">pause/continue</a> the timer pauses and continues when pressed again.

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

My HTML in relevance to the jQuery is here if you need.

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

what i want to achieve is when you click this href <a href="javascript:void(0)" class="pauser">pause/continue</a> the timer pauses and continues when pressed again.

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

My HTML in relevance to the jQuery is here if you need.

<a href="http://myurl." id="download" class="button" style="display: none;font-size:30px;">Continue !!</a><p id="notice">
You can continue in 10 seconds</p>
Share Improve this question edited Nov 16, 2011 at 21:53 Manse 38.1k11 gold badges86 silver badges111 bronze badges asked Nov 16, 2011 at 21:46 Yusaf KhaliqYusaf Khaliq 3,39311 gold badges45 silver badges82 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 7

Well, I would just have your pause event set a boolean, and then check that boolean before you decrement your counter:

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

and

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

and

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

That should do it, right?

发布评论

评论列表(0)

  1. 暂无评论