2012-02-28 91 views
1

我有一個計時器設置像這樣:clearTimeout在鼠標離開

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不取消定時器?謝謝!

回答

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

太神奇了!感謝Jared的快速,簡潔和真棒的迴應。使完美感:) – Aaron 2012-02-28 19:43:11

0

您使用的是同一個變量的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]); 
    } 
});