How to exit from setInterval

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

Answers


Use clearInterval:

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

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

Pass the value of setInterval to clearInterval.

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

Countdown example

The timer is decremented every second, until reaching 0.

let secondsToCountDown = 2

const interval = setInterval(() => {

  // just for presentation
  document.querySelector('.timer').innerHTML = secondsToCountDown

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

  secondsToWait--;
}, 1000);
<p class="timer"></p>

Need Your Help

Can't get GSAP MorphSVG to work

svg greensock gsap

I've set up a simple SVG with two polylines and am trying to morph between them using GSAP's MorphSVG. https://greensock.com/morphSVG

One form with multiple submit actions

javascript php html

I have an HTML with three links and a form, and three PHP scripts: send1.php, send2.php, send3.php.