所以我是新来的,如果这是一个基本问题,我很抱歉,但我在其他地方看不到它的答案。
我正在尝试编写一个显示动画(使用pixijs)的网络应用程序,然后显示一个请求响应的div。我的问题是,因为动画是使用 requestAnimationFrame 处理的,所以动画是异步发生的,因此响应和动画阶段同时发生(div 立即出现并遮盖动画)。
现在我环顾四周,共识似乎是使用回调函数,该函数仅在所有异步工作执行完毕后才会触发,从而允许串行进行。
但是,requestAnimationFrame 采用以下形式
requestAnimationFrame(update_screen_objects),
但是当我尝试这样做时会中断:
requestAnimationFrame(update_screen_objects(response_phase_callback))
显然 requestAnimationFrame 不喜欢传递一个本身有回调的函数。所以我的问题是:我应该对动画循环做什么以确保后续函数在动画完成后执行?
谢谢!
编辑
这是上述形式的代码示例,不起作用。
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.
}
}
最佳答案
不需要复杂的包装器,只需这样做:
requestAnimationFrame(update_screen_objects.bind(window, response_phase_callback))
这个“currys”通过部分应用一些参数来实现 update_screen_objects 函数。 .bind(context, arg1) 的结果是一个函数,在调用时,仅接受尚未绑定(bind)的任何参数,例如 arg2、arg3 等。
关于javascript - 等待 requestAnimationFrame 完成(通过回调),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579511/