首页 文章

ClearInterval不清除SetInterval

提问于
浏览
1

当我们使用SetInterval返回的值调用clearInterval时,它会使该值为null或未定义 .

我调用clearInterval来清除setInterval,但显然setInterval的值保持不变,即使在调用clearInterval后也不会改变 . 被认为是null还是未定义?这是我的代码片段

var setIntervalId; // declared in global scope
//lined of code

function autorefresh() {
  if (statesCount > 0) {
    setIntervalId = setInterval(function() {
        //lines of code
        // calling some handler
    }, 30000);
  }

  if (statesCount === 0) {
    clearInterval(setIntervalId);
  }
}

正如您所看到的,我每隔30秒调用一次setInterval函数,第一次调用时会为setIntervalId赋值,但即使在调用clearInterval之后,该值仍然存在 . 在调用clearInterval之后它应该变为null还是未定义?如果它应该为null或undefined我应该在这里做什么 . 我在全局范围内定义了setIntervalId .

3 回答

  • 3

    函数 clearInterval 不会清除传递给它的值 . 如果你想清除它,你必须自己做

    clearInterval(setIntervalId);
    setIntervalId = undefined;
    

    请注意,您似乎没有正确地保护对 setInterval 的初始调用 . 这可能导致多次调用,因此您有多个间隔设置 . 我认为你应该将你的初始 if 块增加到以下内容

    if (statesCount > 0 && typeof(setIntervalId) === 'undefined') { 
      ...
    }
    
  • 0

    调用clearInterval后它应该变为null还是未定义?

    没有 .

    这只是一个数字 . 当间隔被清除时,该数字只是历史的好奇心 .

    如果您愿意,可以在将 clearInterval 用于 clearInterval 之后为其明确指定 undefined . 除非您使用它来跟踪您的功能当前是否定期运行,否则无需执行此操作 .

  • 5

    如果您当时只允许一个间隔,这应该可以正常工作 .

    如果允许多个间隔,则需要保持对每个实例的访问权限以阻止它们 .

    var setIntervalId; // declared in global scope
    var statesCount = 1; // simulate active state
    //lined of code
    
    
    function autorefresh() {
      if (statesCount > 0) {
        console.log('started');
        setIntervalId = setInterval(function() {
          // just to see whats happening in console
          console.log(statesCount);
    
          // performe interval checks inside the interval loop not outside if you want to stop it automaticaly
          if (statesCount === 0) {
            clearInterval(setIntervalId);
          }
          // lines of code
          // calling some handler
        }, 1000); // repeat every 1s
      };
    }
    
    // run interval
    autorefresh();
    
    // stimulate change of stateCount after 5s
    // setTimeout(function(){
    //   statesCount = 1;
    // },5000);
    
    // clear interval after 10s
    setTimeout(function(){
      clearInterval(setIntervalId);
      console.log('stoped');
    },10000);
    
    • CODEPEN EXAMPLE

相关问题