Skip to content Skip to sidebar Skip to footer

Cleartimeout On Mouse Exit

I have a timer setup like so: var timerID; $this.hover(function(){ $this.find('.stage_obj').each(function(index){ var current_obj = $(this); timerID = setTimeout(fu

Solution 1:

The reason why the timeout isn't cleared is because you set multiple timeouts via the each but only store (and hence clear) one of them. You need to store and clear each of the time out ids you create.

var timerID = [];

$this.hover(function(){
   $this.find('.stage_obj').each(function(index){
      var current_obj = $(this);
      var currentTimerID = setTimeout(function(){
         animate_on_top(current_obj, index);}, parseInt(OS.delay_y_on_set[index],10));
      timerID.push(currentTimerID);
      });   
 }, function(){
   for (var i = 0; i < timerID.length; i++) {
     clearTimeout(timerID[i]);
   }
});

Solution 2:

You are using the same variable timerID in a loop, so for each iteration, the reference gets changed to the last one.

When you clear, you actually clear only the last one, not the references you created !

You should changed your code to pass the list of objects to animate to your method animate_on_top() instead of setting a timer for each of them independantly.

Or you can push the references returned by the different setTimout() calls into an array and clear all the references of the array on mouseout. Something like:

var timerID = [];

$this.hover(function(){
   $this.find('.stage_obj').each(function(index){
      var current_obj = $(this);
      var timer = setTimeout(function(){
         animate_on_top(current_obj, index);}, parseInt(OS.delay_y_on_set[index],10));
      });   
      timerID.push(timer);
 }, function(){
   for (var i = 0; i < timerID.length; i++) {
     clearTimeout(timerID[i]);
   }
});

Post a Comment for "Cleartimeout On Mouse Exit"