How to exit from setInterval
Asked Answered
G

3

100

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);
Graticule answered 25/11, 2009 at 6:53 Comment(0)
D
211

Use clearInterval:

var refreshId = setInterval(function() {
  var properID = CheckReload();
  if (properID > 0) {
    clearInterval(refreshId);
  }
}, 10000);
Duke answered 25/11, 2009 at 6:55 Comment(3)
just call clearInterval(intervalName), for example: var helloEverySecond = setInterval(function() { console.log("hello");}, 1000); can be stopped by clearInterval(helloEverySecond);Festination
This is a whole new level of ugly from Javascript. Referencing a variable inside its own declaration.Babyblueeyes
Why is it ugly @Babyblueeyes ? Doesn't clearInterval clean up properly?Fontainebleau
F
17

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>
Fontainebleau answered 1/5, 2019 at 6:24 Comment(0)
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
);
}
Pero answered 7/3, 2019 at 17:41 Comment(1)
What role do braces around refreshId play? Thanks.Dong

© 2022 - 2024 — McMap. All rights reserved.