I have something like this:

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

I try to clear the timeout/interval like so:

clearInterval( activityTextToggleTimerTwo );
clearTimeout( activityTextToggleTimerThree );

I get an exception:

Uncaught ReferenceError: activityTextToggleTimerThree is not defined 

Why? Also i think the activityTextToggleTimerThree does not get cleared..

Thanks

有帮助吗?

解决方案

Your variable is out of scope, because it's defined inside the callback to setInterval. You have to move it to the outer scope, but you may still have a problem: every time the setInterval callback is executed, you'll be replacing the timer handler in that variable, so you'll only be able to clear the latest setTimeout timer.

其他提示

Put the .clearInterval() method inside the .setInterval() anonymous function, like:

// 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() won't need to be cleared using this methodology.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top