【问题标题】:Nested setInterval and setTimeout嵌套 setInterval 和 setTimeout
【发布时间】:2013-09-21 06:22:30
【问题描述】:

我有这样的事情:

var activityTextToggleTimerTwo = setInterval(function() {
    active_users_text.toggleClass("active inactive bounce bounceOutUp")
    var activityTextToggleTimerThree = setTimeout(function() {
        active_users_text.toggleClass("active inactive bounce bounceOutUp");
    }, 5000);
}, 25000);

我尝试像这样清除超时/间隔:

clearInterval( activityTextToggleTimerTwo );
clearTimeout( activityTextToggleTimerThree );

我得到一个例外:

Uncaught ReferenceError: activityTextToggleTimerThree is not defined 

为什么?我也认为 activityTextToggleTimerThree 没有被清除..

谢谢

【问题讨论】:

  • 你不能清除activityTextToggleTimerThree,因为它是一个函数。

标签: javascript settimeout setinterval clearinterval


【解决方案1】:

您的变量超出范围,因为它是在setInterval 的回调中定义的。您必须将其移至外部范围,但您可能仍然遇到问题:每次执行 setInterval 回调时,您将替换该变量中的计时器处理程序,因此您只能清除最新的setTimeout 计时器。

【讨论】:

  • 感谢您指出我将只清除“最新”计时器...那么我该怎么做呢?谢谢
  • 如果需要清除多个计时器,可以将它们的处理程序保存在一个数组中。
【解决方案2】:

.clearInterval()方法放在.setInterval()匿名函数里面,比如:

// assuming you have active_users_text defined
var rotations = 0;
var activityTextToggleTimerTwo = setInterval(function(){
  active_users_text.toggleClass('active inactive bounce bounceOutUp');
  // change 1 if you want
  if(rotations < 1){
    var activityTextToggleTimerThree = setTimeout(function(){
      active_users_text.toggleClass('active inactive bounce bounceOutUp');
    }, 5000);
  }
  // change 75000 if you want
  if(rotations++ == 75000){
    clearInterval(activityTextToggleTimerTwo);
  }
}, 25000);

setTimeout() 不需要使用此方法清除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多