Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is requestAnimationFrame implementation's recursive?

I'm currently experimenting with three.js, which relies on requestAnimationFrame to perform animations.

Wouldn't the following code result in infinite recursion before the cube rotations and renderer.render function are invoked?

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?

like image 551
thelittlegumnut Avatar asked Mar 21 '15 09:03

thelittlegumnut


2 Answers

This only requests the browser to call your callback before the next rendering loop:

You should call this method whenever you're ready to update your animation onscreen. This will request that your animation function be called before the browser performs the next repaint.

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.

like image 162
eladcon Avatar answered Sep 27 '22 21:09

eladcon


No, the stack won't blow because requestAnimationFrame's callback is executed asynchronously. Async code is never run until the entire call stack is cleared. See this video for an explanation of the event loop.

Consider this demo to illustrate:

const fakeRAF = cb => setTimeout(cb);

(function rerender() {
  fakeRAF(rerender);
  console.log(Date.now());
})();

You can let this run all day. Of course, requestAnimationFrame is doing much more work than fakeRAF by essentially being very clever about computing when to fire cb, but this simple demo is sufficient to prove that it's not recursive, thanks to setTimeout providing an asynchronous API.

By the way, it doesn't matter whether requestAnimationFrame or fakeRAF is called at the top or the bottom of the function. All of the synchronous code in the function must run before the callback is fired so there is no issue of the next frame stepping on the previous one or something like that.

like image 41
ggorlen Avatar answered Sep 27 '22 22:09

ggorlen