1

所以我是新來的,道歉,如果這是一個基本的問題,但我看不到它在其他地方回答。等待requestAnimationFrame完成(通過回調)

我想寫一個顯示動畫(使用pixijs)的webapp,然後顯示一個請求響應的div。我的問題是,因爲動畫是使用requestAnimationFrame處理的,所以動畫是異步發生的,所以響應和動畫階段同時發生(div立即出現並遮擋動畫)。

現在我看了看周圍,似乎共識似乎是使用回調函數,只有在執行完所有異步工作後纔會觸發回調函數,從而允許序列進度。

然而,requestAnimationFrame的形式爲

requestAnimationFrame(update_screen_objects)

,但休息時,我嘗試做:

requestAnimationFrame(update_screen_objects(response_phase_callback))

很明顯,requestAnimationFrame不喜歡被傳遞一個本身具有回調函數。所以我的問題是:我應該怎樣做動畫循環以確保後續函數在動畫完成後執行?

謝謝!

EDIT

這是在上述形式工作的代碼的一個例子。

function animate(callback) { 

var finished = false; 

if ((new Date().getTime()) < adaptTime){ 
    runFlicker(false); 
} else if ((new Date().getTime()) < judgeTime){ 
    hideAdaptors(); 
} else if ((new Date().getTime()) > judgeTime){ 
    stage.visible = false;   
    finished = true;     
} 
renderer.render(stage); 

if (!finished){ 
    requestAnimationFrame(animate(callback)); //Ensures it will keep looping 
    //requestAnimationFrame(animate); //This does work, but my issue still persists 
} else { 
    callback(); //By the time callback() is required, you can't access it as requestAnimationFrame doesn't accept animate() with a function passed to it. 
} 
} 
+0

'requestAnimationFrame'不會將參數傳遞給函數 – Markasoftware 2014-10-27 00:27:18

+0

你的第二次嘗試*調用函數,而不是*傳遞*。相反,傳遞一個調用'update_screen_objects'函數並傳遞迴調的函數表達式。 – Bergi 2014-10-27 00:34:29

+0

我們可以有你的代碼的例子嗎? – YoannM 2014-10-27 01:12:09

回答

0

試試看。您基本上需要用回調生成該步驟(animate),而不是將您的呼叫結果傳遞給animate,這將是undefined

function generateAnimation(callback) { 

    function step() { 

    var finished = false; 
    var now = (new Date()).getTime(); 

    if (now < adaptTime) { 
     runFlicker(false); 
    } else if (now < judgeTime) { 
     hideAdaptors(); 
    } else if (now > judgeTime) { 
     stage.visible = false; 
     finished = true; 
    } 

    renderer.render(stage); 

    if (!finished) { 
     requestAnimationFrame(step); 
    } else { 
     callback(); 
    } 

    } 

    return step; 

} 

// Usage: 
requestAnimationFrame(generateAnimation(callback)); 
+0

謝謝兄弟!所以爲了完全理解這裏發生了什麼,使用包裝器函數generateAnimation(callback),它允許step()和回調函數仍然在作用域內? – kaifresh 2014-10-29 23:58:44

+0

正確。基本上,爲了對我的答案進行重新說明,你想要的是一個'step'版本,它可以調用'callback',你可以傳遞給rAF,而不是用'callback'調用'step',並將調用結果傳遞給rAF 。 – hlfcoding 2014-10-30 00:06:00

2

無需複雜的包裝,只是做:

requestAnimationFrame(update_screen_objects.bind(window, response_phase_callback)) 

這種 「currys」 的update_screen_objects功能通過部分應用一些爭論。 .bind(context,arg1)的結果是一個函數,當被調用時,它只接受任何尚未綁定的參數,例如arg2,arg3等。