为什么在循环开始时调用requestAnimationFrame不会导致无限递归? [英] Why does calling requestAnimationFrame at the beginning of a loop not cause infinite recursion?
问题描述
这是怎么回事,它允许循环的其余部分执行,然后让requestAnimationFrame
执行下一帧?
What is going on that allows the rest of the loop to execute, and then for requestAnimationFrame
to execute next frame?
我误解了这种方法的工作原理,在任何地方都看不到清晰的解释.我尝试在此处阅读时序规范 http://www.w3.org/TR/animation-时间/,但我无法确定它是如何工作的.
I am misunderstanding how this method works, and can't see a clear explanation anywhere. I tried reading the timing specification here http://www.w3.org/TR/animation-timing/ but I couldn't make out how it worked.
例如,此代码摘自threejs文档.
For example, this code is taken from the threejs documentation.
var render = function () {
requestAnimationFrame(render);
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
};
推荐答案
请让我知道我是否完全脱离基地;我以前没有用过动画的东西.我看到的使用requestAnimationFrame
的示例是:
Please let me know if I am completely off-base; I haven't used the animation stuff before. An example I saw for using requestAnimationFrame
is:
(function animloop(){
requestAnimFrame(animloop);
render();
})();
您是否想知道为什么animloop
传递给requestAnimFrame
时,随后调用它时不会导致无限循环?
Are you wondering why animloop
as it is passed into requestAnimFrame
doesn't cause an infinite loop when it is subsequently called?
这是因为此函数不是真正递归的.您可能会认为调用requestAnimFrame
时会立即调用animloop
.不是这样! requestAnimFrame
是异步的.因此,将按照您看到的顺序执行语句.这意味着主线程不会等待,而在render()
调用之前 之前,返回对requestAnimFrame
的调用.因此render()
几乎立即被调用.但是,回调 not 不会立即被调用(在本例中为animloop
).当您已经退出对animloop
的 first 调用时,将来可能会调用 .对animloop
的此新调用具有其自身的上下文和堆栈,因为实际上尚未从第一个animloop
调用的执行上下文中的内部进行调用.这就是为什么您不会最终得到无限递归和堆栈溢出的原因.
This is because this function isn't truly recursive. You might be thinking that animloop
is immediately called when you call requestAnimFrame
. Not so! requestAnimFrame
is asynchronous. So the statements are executed in the order that you see. What this means is that the main thread does not wait for the call to requestAnimFrame
to return, before the call to render()
. So render()
is called almost immediately. However the callback (which in this case is animloop
) is not called immediately. It may be called at some point in the future when you have already exited from the first call to animloop
. This new call to animloop
has its own context and stack since it hasn't been actually called from within the execution context of the first animloop
call. This is why you don't end up with infinite recursion and a stack overflow.
这篇关于为什么在循环开始时调用requestAnimationFrame不会导致无限递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!