10 start stop $('#start').click(function(){ var c = $(...">

How to stop setInterval?

<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 should I rewrite this to use STOP correctly?

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

+2
javascript jquery html
Dec 12 '11 at 14:44
source share
3 answers

inter should be available for both functions. Wrap both functions with closure so that you can avoid contaminating the global namespace of the 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)); 
+5
Dec 12 '11 at 14:48
source share

inter is a local variable.
It does not exist outside of your callback.

You need to use a global variable.

+3
Dec 12 '11 at 14:46
source share
 var inter = 0;
 $ ('# start'). click (function () {
     var c = $ ('# ccc'). text ();
          inter = setInterval (function () {
                     c--;
                     $ ('# ccc'). text (c);
             }, 1000);
 }); 

 $ ('# stop'). click (function () {
      clearInterval (inter);
     });
+2
Dec 12 '11 at 2:47 a.m.
source share



All Articles