正在等待requestAnimationFrame完成(通过回调)

waiting for requestAnimationFrame to finish (via callbacks)

本文关键字:回调 在等待 requestAnimationFrame 完成      更新时间:2023-09-26

所以我是新来的,如果这是一个基本问题,我很抱歉,但我在其他地方看不到答案。

我正在尝试编写一个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));