4

Possible Duplicate:
Stop setInterval call in javascript

I use window.setInterval method for polling progress status. But need to disable this timer when it completed. How to disable timer?

      window.setInterval(function(){$.ajax({
          type: 'GET',
          url: 'imports',
          success: function(response){
            console.log(response);
            if(response['status'] != 'ok'){
              return;
            }

            $('.bar').css('width', response['progress'] + '%');

            if(response['step'] == 'completed') location.reload();
      }}, 'json');}, 1000);
Community
  • 1
  • 1
Denis Kreshikhin
  • 8,856
  • 9
  • 52
  • 84
  • 2
    Probably duplicate - http://stackoverflow.com/q/109086/1947535 – m.brindley Feb 03 '13 at 12:03
  • 2
    [MDN](https://developer.mozilla.org/en-US/docs/DOM/window.setInterval) is a really good JS reference if you're not sure how a particular function works. – nnnnnn Feb 03 '13 at 12:24

4 Answers4

3

When you start the interval it returns an integer defining it:

var timer = window.setInterval( ... );

You can then clear that interval when your AJAX function returns true:

...
success: function(response) {
  console.log(response);
  if (response['status'] != 'ok') {
    clearInterval(timer);
    return;
  }
}
...
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Jivings
  • 22,834
  • 6
  • 60
  • 101
2

the setInterval() method will return an integer/number. You need to store this, then pass it to the method clearInterval() to stop it.

var intervalId = window.setInterval(.....);

then later, when you want to stop it, I think it would go:

window.clearInterval(intervalId);
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
mitim
  • 3,169
  • 5
  • 21
  • 25
2

setInterval() returns a handle which you can later pass to window.clearInterval() to stop the timer.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1
var x = window.setInterval(...);
// ...
window.clearInterval(x);
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Nir Aviel
  • 99
  • 1
  • 8