clearTimeout on Mouse Exit

笑着哭i 提交于 2020-01-15 18:56:43

问题


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(function(){
         animate_on_top(current_obj, index);}, parseInt(OS.delay_y_on_set[index],10));
      });   
}, function(){
   clearTimeout(timerID);
});

There are functions to control the animation in/out on hover. The timers are acting as delays (.delay won't work in my situation). Everything works fine, except the timer isn't cancelled on mouse exit, and still fires. Here's the actual animation_on function being called:

function animate_on_top(current_obj, index){ 
   current_obj.animate(
      {'top':OS.ends_y_set[index]},
      {duration:500, queue:false,
      specialEasing:{'top':'linear'}
});

Anyone have any ideas why the setTimeout isn't cancelling the timer? Thanks!


回答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]);
   }
});



回答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]);
   }
});


来源:https://stackoverflow.com/questions/9488311/cleartimeout-on-mouse-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!