【问题标题】:How to exit from setInterval如何退出 setInterval
【发布时间】:2009-11-25 06:53:58
【问题描述】:

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

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

【问题讨论】:

    标签: javascript setinterval


    【解决方案1】:

    使用clearInterval:

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

    【讨论】:

    • 只需调用clearInterval(intervalName),例如:var helloEverySecond = setInterval(function() { console.log("hello");}, 1000);可以被clearInterval(helloEverySecond);停止
    • 这是 Javascript 的一个全新级别的丑陋。在自己的声明中引用变量。
    • 为什么@Prime624 这么丑? clearInterval 不能正确清理吗?
    【解决方案2】:

    setInterval 的值传递给clearInterval

    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);
    &lt;p&gt;&lt;/p&gt;

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • refreshId 周围的大括号起什么作用?谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-26
      • 1970-01-01
      相关资源
      最近更新 更多