I'm currently experimenting with three.js, which relies on requestAnimationFrame to perform animations.
Question: Wouldn't the following code result in infinite recursion before the cube rotations and renderer.render function invocation?
function render() {
requestAnimationFrame(render);
cube.rotation.x += 0.1;
cube.rotation.y += 0.1;
renderer.render(scene, camera);
}
render();
The code works, but I'm trying to improve my overall understanding of javascript.
The way I see it, is that render is invoked as a callback function. But does that mean that javascript continues running through the code in the function before stopping to move on to the next call?
The simplest usage of requestanimationframe is to call it again and again until it is not necessary
I learned this lesson while I develop a small library
https://github.com/allenhwkim/jsanimation
Usage
This only requests the browser to call your callback before the next rendering loop:
So there is no recursion here, and your function continue with the execution.
You can also cancel the request for your callback with
cancelAnimationFrame
.Look here.
After the first render() call, RequestAnimationFrame will asynchronously take care of your render function calling it every ~60 times per second. Your function is not recursive, since Javascript will continue the code execution.
However, you should use RequestAnimationFrame only at the very end of your render function, as last command of your function. Imagine you having a big scene, with a lot of animations: requesting the next frame before completing parameters update, will probably cause a huge mess.
You can also use setTimeout to handle your animations, calling the render method with the desired frame rate, like this: