为什么在循环开始时调用requestAnimationFrame不会导致无限递归? [英] Why does calling 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-timing / ,但我不知道它是如何工作的。
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?
't 真正递归。您可能会认为 animloop
会在调用 requestAnimFrame
时立即调用。不是! requestAnimFrame
是异步的。因此,将按照您看到的顺序执行语句。这意味着主线程不等待,在之前调用 requestAnimFrame
返回 render()
。因此 render()
几乎立即被调用。但是,将立即不调用回调(在本例中为 animloop
)。当您已经退出 first 调用 animloop
时,将来可能会调用 。对 animloop
的新调用具有其自身的上下文和堆栈,因为实际上并未从之内的第一个<$ c执行上下文真正调用它$ c> 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屋!