为什么在循环开始时调用requestAnimationFrame不会导致无限递归? [英] Why does calling requestAnimationFrame at the beginning of a loop not cause infinite recursion?

查看:233
本文介绍了为什么在循环开始时调用requestAnimationFrame不会导致无限递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是怎么回事,它允许循环的其余部分执行,然后让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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆