How to exit from setInterval

JavascriptSetinterval

Javascript Problem Overview


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);

Javascript Solutions


Solution 1 - Javascript

Use clearInterval:

var refreshId = setInterval(function() {
  var properID = CheckReload();
  if (properID > 0) {
    clearInterval(refreshId);
  }
}, 10000);

Solution 2 - Javascript

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>

Solution 3 - Javascript

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
);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartin OngtangcoView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptTobias Goulden SchultzView Answer on Stackoverflow
Solution 3 - JavascriptrovykoView Answer on Stackoverflow