如何退出setInterval

时间:2009-11-25 06:53:59

标签: javascript setinterval

如果条件正确,我需要退出运行间隔:

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

3 个答案:

答案 0 :(得分:118)

使用clearInterval

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

答案 1 :(得分:1)

已针对ES6更新

您可以设置变量的作用域,以避免污染名称空间:

const CheckReload = (() => {
  let counter = - 5;
  return () => {
    counter++;
    return counter;
  };
})();

{
const refreshId = setInterval(
  () => {
    const properID = CheckReload();
    console.log(properID);
    if (properID > 0) {
      clearInterval(refreshId);
    }
  },
  100
);
}

答案 2 :(得分:0)

setInterval的值传递给clearInterval

简单示例

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

倒数示例

计时器每秒钟递减,直到达到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>


带分隔符的倒计时示例

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>