开发者

How to exit from setInterval

I need to exit from a running interval if the condit开发者_开发知识库ions are correct:

var refreshId = setInterval(function() {
        var properID = CheckReload();
        if (properID > 0) {
            <--- exit from the loop--->
        }
    }, 10000);


Use clearInterval:

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


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>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜