How to stop setInterval?

2019-07-20 02:10发布

<span id="ccc">10</span> <span id="start">start</span> <span id="stop">stop</span>

$('#start').click(function(){
    var c = $('#ccc').text();
         var inter =   setInterval(function() {
                    c--;
                    $('#ccc').text(c);
            }, 1000);
}); 

$('#stop').click(function(){
     clearInterval(inter);
    });

how i must rewrite this for correctly use STOP?

LIVE: http://jsfiddle.net/c3hZh/

3条回答
Lonely孤独者°
2楼-- · 2019-07-20 02:37

inter is a local variable.
It doesn't exist outside your callback.

You need to use a global variable.

查看更多
干净又极端
3楼-- · 2019-07-20 02:47
var inter = 0;
$('#start').click(function(){
    var c = $('#ccc').text();
         inter =   setInterval(function() {
                    c--;
                    $('#ccc').text(c);
            }, 1000);
}); 

$('#stop').click(function(){
     clearInterval(inter);
    });
查看更多
狗以群分
4楼-- · 2019-07-20 02:50

inter needs to be in-scope for both functions. Wrap both functions with a closure so that you can avoid polluting the global namespace with a new variable.

(function ($) {
  var inter;

  $('#start').click(function(){
    var c;
    c = parseInt($('#ccc').text()); //make sure you're getting a numeric value
    //don't forget to clear any existing interval before setting a new one:
    if (inter) {
      clearInterval(inter);
    }
    inter = setInterval(function() {
      c--;
      $('#ccc').text(c);
    }, 1000);
  });

  $('#stop').click(function() {
    clearInterval(inter);
  });
}(jQuery));
查看更多
登录 后发表回答