2013-07-31 49 views
0

我已經嘗試了幾種不同的方式,除了正確的。setTimeout /暫停/等

試圖這樣:

setTimeout(function() { 
    $('.historyTextBoxes p') 
    .bind('showText', function(e) { 
     $(this).fadeIn(800, function(){ 
      $(this).next().length && $(this).next().trigger("showText"); 
     }); 
    }).eq(0).trigger('showText'); 
}, 4000); 

將等待4秒,然後淡入,一個每個段落之後另一個在0.800毫秒的速度。

我想要做的是在0.800毫秒淡入一個段落,然後等待4秒下一段落中消失之前

的基本設置:

$('.historyTextBoxes p') 
.bind('showText', function(e) { 
    $(this).fadeIn(800, function(){ 
     $(this).next().length && $(this).next().trigger("showText"); 
     alert('pause here'); 
    }); 
}).eq(0).trigger('showText'); 

作品但是我還沒有找到正確的語法來讓它停留在警報的位置。

我試圖拋出調用一個函數,但我並不需要運行,除了是因爲要等待什麼。

因此,在僞代碼中,我試圖定義是這樣的:

function wait() { 
    pause(for 4 seconds); 
} 

然後我可以調用該函數,而不是上面的警報。我的問題setTimeout已'定義一個函數',但我在想什麼。

+1

你的意思是這樣的? http://roxon.in/scripts/fademe_jquery_plugin/ –

+0

非常整潔,但它似乎是週期性的。雖然好發現。 –

回答

1

使用setTimeout是正確的,但你在錯誤的地方應用它。

$('.historyTextBoxes p').bind('showText',function(e) { 
    $(this).fadeIn(800,function(){ 
    // this is the callback after the fadein 
    // here we want to wait (use a timeout) 
    var next = $(this).next(); 
    if (next.length) 
     setTimeout(function() { 
     // before the next text is shown 
     next.trigger("showText"); 
     }, 4000); 
    }) 
}).eq(0).trigger('showText'); 
+0

謝謝,完美!我現在看到我的錯誤。 –

1

這應做到:

function showAll() { 
    var p = $('.historyTextBoxes p').get(); // array of elements 

    (function loop() { 
     if (p.length) { 
      var el = p.shift(); 
      $(el).fadeIn(800).delay(4000).promise().done(loop); 
     } 
    })(); 
} 

演示在http://jsfiddle.net/4dNr3/2/

注意,這裏使用沒有明確的計時器在所有,也不使用任何事件觸發下一個階段 - 它依靠所有時機的動畫隊列。請注意,這不是一般一個好主意,混合定時器和動畫,除非你能保證他們的交錯,而不是並行運行。不過,在這種情況下沒問題。

+0

我給你一個,因爲這很酷。以前沒有見過這個'承諾'。感謝您的意見。 –