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等。