How to exit from setInterval

南楼画角 提交于 2019-11-28 17:44:55

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>

Countdown example with separation

let secondsToCountDown = 2

const doStuffOnInterval = () => {
  document.querySelector('.timer').innerHTML = secondsToCountDown

  if (secondsToCountDown === 0) {
    stopInterval()
  }

  secondsToCountDown--;
}

const stopInterval = () => {
  clearInterval(interval);
}

const interval = setInterval(doStuffOnInterval, 1000);
<p class="timer"></p>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!