How to exit from setInterval

*爱你&永不变心* 提交于 2019-11-27 10:41:11

问题


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

回答1:


Use clearInterval:

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



回答2:


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



回答3:


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>


来源:https://stackoverflow.com/questions/1795100/how-to-exit-from-setinterval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!