【问题标题】:clearTimeout on Mouse Exit鼠标退出时清除超时
【发布时间】:2012-02-28 19:22:27
【问题描述】:

我有一个这样的计时器设置:

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

有一些功能可以控制悬停时的动画进/出。计时器充当延迟(.delay 在我的情况下不起作用)。一切正常,除了鼠标退出时定时器没有取消,并且仍然触发。下面是实际调用的 animation_on 函数:

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

有人知道为什么 setTimeout 没有取消计时器吗?谢谢!

【问题讨论】:

    标签: javascript jquery timer settimeout


    【解决方案1】:

    未清除超时的原因是因为您通过each 设置了多个超时,但只存储(并因此清除)其中一个。您需要存储并清除您创建的每个超时 ID。

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

    【讨论】:

    • 太棒了!感谢 Jared 的快速、简洁和出色的回复。很有道理:)
    【解决方案2】:

    您在循环中使用相同的变量 timerID,因此对于每次迭代,引用都会更改为最后一个。

    当你清除时,你实际上只清除了最后一个,而不是你创建的引用!

    您应该更改代码以将要设置动画的对象列表传递给您的方法animate_on_top(),而不是为每个对象单独设置一个计时器。

    或者您可以将不同 setTimout() 调用返回的引用推送到一个数组中,并在鼠标移出时清除该数组的所有引用。比如:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-05
      • 1970-01-01
      • 2011-06-09
      • 2014-11-29
      • 2011-10-05
      • 2012-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多