93

I need to exit from a running interval if the conditions are correct:

var refreshId = setInterval(function() {
        var properID = CheckReload();
        if (properID > 0) {
            <--- exit from the loop--->
        }
    }, 10000);
Mooseman
  • 18,763
  • 14
  • 70
  • 93
Martin Ongtangco
  • 22,657
  • 16
  • 58
  • 84

3 Answers3

203

Use clearInterval:

var refreshId = setInterval(function() {
  var properID = CheckReload();
  if (properID > 0) {
    clearInterval(refreshId);
  }
}, 10000);
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
14

Pass the value of setInterval to clearInterval.

const interval = setInterval(() => {
  clearInterval(interval);
}, 1000)

Demo

The timer is decremented every second, until reaching 0.

let secondsRemaining = 10

const interval = setInterval(() => {

  // just for presentation
  document.querySelector('p').innerHTML = secondsRemaining

  // time is up
  if (secondsRemaining === 0) {
    clearInterval(interval);
  }

  secondsRemaining--;
}, 1000);
<p></p>
3

Updated for ES6

You can scope the variable to avoid polluting the namespace:

const CheckReload = (() => {
  let counter = - 5;
  return () => {
    counter++;
    return counter;
  };
})();

{
const refreshId = setInterval(
  () => {
    const properID = CheckReload();
    console.log(properID);
    if (properID > 0) {
      clearInterval(refreshId);
    }
  },
  100
);
}
rovyko
  • 4,068
  • 5
  • 32
  • 44