82

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

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

3 回答 3

184

使用clearInterval

var refreshId = setInterval(function() {
  var properID = CheckReload();
  if (properID > 0) {
    clearInterval(refreshId);
  }
}, 10000);
于 2009-11-25T06:55:57.387 回答
12

将 的值传递setIntervalclearInterval

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

演示

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

于 2019-05-01T06:24:42.317 回答
2

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

于 2019-03-07T17:41:19.640 回答