嵌套的 setInterval 和 setTimeout

Nested setInterval and setTimeout

本文关键字:setTimeout setInterval 嵌套      更新时间:2023-09-26

我有这样的东西:

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 

为什么?另外,我认为活动TextToggleTimerThree不会被清除。

谢谢

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

.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()不需要使用此方法清除。