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
  • 7,996
  • 8
  • 48
  • 81
  • 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
  • 156,572
  • 25
  • 250
  • 300
Jivings
  • 22,276
  • 6
  • 54
  • 98
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
  • 156,572
  • 25
  • 250
  • 300
mitim
  • 3,179
  • 5
  • 20
  • 24
1

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

Michael Borgwardt
  • 335,521
  • 76
  • 467
  • 706
1
var x = window.setInterval(...);
// ...
window.clearInterval(x);
Dave Newton
  • 156,572
  • 25
  • 250
  • 300
Nir Aviel
  • 99
  • 8