Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top