正在等待requestAnimationFrame完成(通过回调)
waiting for requestAnimationFrame to finish (via callbacks)
所以我是新来的,如果这是一个基本问题,我很抱歉,但我在其他地方看不到答案。
我正在尝试编写一个Web应用程序,它显示一个动画(使用pixijs),然后显示一个请求响应的div。我的问题是,因为动画是使用requestAnimationFrame处理的,所以动画是异步发生的,因此响应和动画阶段是同时发生的(div会立即出现并遮挡动画)。
现在我环顾四周,一致认为应该使用回调函数,只有在执行完所有异步工作后才会触发该函数,从而允许串行进程。
但是,requestAnimationFrame采用形式
requestAnimationFrame(update_screen_objects) ,
但当我尝试做时会崩溃
requestAnimationFrame(update_screen_objects(response_hase_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)的结果是一个函数,当调用该函数时,它只接受任何尚未绑定的参数,例如arg2、arg3等。
试试这个。您基本上需要通过回调生成步骤(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));
- AJAX 回调在 Firefox 中失败
- 回调在 Angular2/Firebase 中生成“TypeError: this is undefined”
- 使用回调在可用时传递消息
- 挂起的回调:在每次回调返回之前返回响应
- 为什么ajax回调在我的本地变量中设置undefined
- jQuery.fadeIn()和.fadeOut()回调在将代码重写为递归回调后无法正常工作
- nodejs:setImmediate 回调在 setTimeout(fn, 0) 之后执行,与 nodejs 文档描述
- spawn() 函数的“关闭”回调在 grunt 插件中不起作用
- Modernizr.load 回调在加载脚本之前执行
- 事件回调在 Mozilla Firefox 中未触发
- 使用回调在数组上执行函数
- JavaScript 回调在主线程中执行
- 角度指令内的回调在模型更新之前调用
- jQuery ajax done 回调在 Firefox 中表现得很奇怪
- Javascript 接口回调在 android webview API 中不起作用 >= 21 与 GWT 2.7 j
- jQuery 回调在声明完成时不触发:
- 如何在调用回调之前等待异步创建的对象完全可用?
- 我如何等待一个回调在coffeescript(或javascript)
- 在javascript中使用承诺/回调来等待函数完成
- 如何在Jquery中等待函数(没有回调)在执行下一个语句之前运行