2012-01-03 68 views
1

我有一個函數調用runUpdates我通過JSON對象的數組來。該函數查看對象,並通過if語句來決定它是什麼樣的更新以及處理該更新應該採取的方向。在某些情況下,更新有一個與之相關的動畫。我想使用jQuery的動畫來爲這些動畫添加動畫,但我希望它在繼續下一步之前等待動畫完成。如何讓我的腳本等待jQuery動畫完成?

我的程序看起來像這 -

runUpdates(updates) { 
    for(i = 0; i < updates.length; i++) { 
     update = updates[i]; 
     if(update.type = "blabla") { 
      //do stuff 
     } else { 
      //do other stuff 
      if(update.animations) { 
       for(k = 0; k < animations.length; k++) { 
        //do jquery animate AND wait for animation to finish before proceeding 
       } 
      } 
     } 
    } 
} 

但是腳本會繼續在動畫開始之後繼續執行。有沒有簡單的方法來解決這個問題,或者我需要重新調用函數調用的循環?

+0

沒有動畫具有動畫結束事件? – 2012-01-03 01:31:27

+2

我懷疑你將不得不重構循環來使用函數調用。 jQuery的'.animate()'有一個完整的回調函數,可以用來啓動流程中的下一步。 – nnnnnn 2012-01-03 01:49:27

+0

*看起來像這樣* - 爲什麼不告訴我們一些**真正的**代碼? – ThiefMaster 2012-01-03 02:30:02

回答

3

你不是在你的問題很清楚什麼是你需要等待。我假設你想等待每個動畫完成,然後繼續下一個動畫。

var pipe = $.Deferred().resolve(); 

for(var k = 0; k < animations.length; k++) 
{ 
    pipe = pipe.pipe(function() 
    { 
     return $('element').animate({ 
      // animate whatever you want 
     }, 300); 
    }); 
} 

這裏有一個演示:http://jsfiddle.net/ZyS6c/


如果你再想把所有的動畫完成後運行一些代碼,把它放在一個done功能:

pipe.done(function() 
{ 
    // Put your code here... 
}); 

.. 。而這裏的小提琴:http://jsfiddle.net/ZyS6c/1/


如果你不感興趣的鏈接動畫(你希望他們異步執行),且只希望所有的動畫完成後,運行一些代碼,使用:

var deferreds = []; 

for(var k = 0; k < animations.length; k++) 
{ 
    deferreds.push(
     $('element').animate({ 
      // animate whatever you want 
     }, 300) 
    ); 
} 

$.when.apply($, deferreds).done(function() 
{ 
    // Put your code here... 
}); 

...和最後,這裏是爲小提琴:http://jsfiddle.net/pdDME/

+0

相反鏈接與'pipe'所有動畫的承諾,更自然的方式就是等待與'jQuery.when'多個承諾。 – 2012-01-03 02:07:14

+0

@Ates Goral - 你能編輯我的小提琴並在這裏發佈鏈接嗎?我不確定我是否關注你。你將如何用'when'來實現? – 2012-01-03 02:09:56