2012-03-29 100 views
0

我有這個估計。我有一個setTimeout函數,其中我淡出和淡入元素。在幾秒鐘內,這個超時被清除,並且在被調用.hide()後立即隱藏這個元素。問題是有時它不隱藏元素。我有一種感覺,它與時間有關。cleartimeout函數完成後執行(jQuery)

例子:

function first_func(){ 
    $('.element').fadeOut(function(){ 
     // Do other stuff like change element's position 
     $('.element').fadeIn(); 
    }); 

    interval1 = setTimeout(function(){first_func()},500);   
} 

function second_func(){ 
    countdown--; 
    if (countdown<0){ 
     last_func(); 
    } 
    interval2 = setTimeout(function(){second_func()},1000);   
} 

function begin_func(){ 
    first_func(); 
    second_func(); 
} 

function last_func(){ 
    clearTimeout(interval1); 
    clearTimeout(interval2); 
    $('.element').hide(); 
} 

所以基本上問題是,在last_func我同時清除間隔和隱藏元素,但有時該元素的網頁上仍然可見。所以我猜測,它並隱藏,但間隔仍在進行中,並在消失回去。

如果有人有一些建議,請

回答

2

只是一個建議,但該位出現錯誤的對我說:

function second_func(){ 
    countdown--; 
    if (countdown<0){ 
     end_func(); 
    } 
    interval2 = setTimeout(function(){second_func()},1000);   
} 

即使你打電話end_func()停止一切,你設置後,一個新的超時。

function second_func(){ 
    countdown--; 
    if (countdown<0){ 
     end_func(); 
    } else { 
     interval2 = setTimeout(second_func, 1000); 
    }  
} 

另一個提示:爲了避免運行淡入/ fadeOuts影響元素的隱藏,你應該清除動畫隊列:

$('.element').stop(true, true).hide(); 
+0

對不起,我一直在從頭開始寫它,我現在沒有我的實際來源。當然在調用end_func()之後;我確實回來了;以及。基本上一切工作都很好,只是有時元素不會隱藏 – Tom 2012-03-29 09:14:49

+0

@Tom ok,但考慮在調用hide之前添加'stop(true,true)',這可能有所幫助。 – Niko 2012-03-29 09:17:13

+0

好吧,我想最好向您展示真實的代碼,您可以在www.tomasdostal.com/projects/thirst_game上看到它。但代碼很雜亂 – Tom 2012-03-29 09:18:03

0

你似乎永遠不會調用last_func,是end_func()應該是last_func()?

這工作: http://jsfiddle.net/CZ9hr/1/

我可能會建議你彷彿想要實現更簡單的方法:http://jsfiddle.net/fSEjR/2/

var countdown = 3, 
    $element = $('.element'); 

for (var i = 0; i < countdown; i++) { 
    $element.fadeOut().fadeIn(function() { 
     countdown--; 
     if (countdown === 0) $element.hide(); 
    }); 
}; 

這工作,因爲動畫在jQuery的自動排隊。

+0

您可以檢查自己www.tomasdostal.com/projects/thirst_game ,有時元素不會隱藏 – Tom 2012-03-29 09:18:49

0

默認情況下,fadeIn和fadeOut使用持續時間爲400毫秒,你可以通過設置第一個參數來改變它。

$('.element').fadeOut([duration] [, callback]); 
+0

這只是一個例子,在我的腳本中,我的持續時間設置爲50 – Tom 2012-03-29 09:15:15

相關問題