Search code examples
javascriptanimationstack-overflowrequestanimationframe

Why does calling requestAnimationFrame at the beginning of a loop not cause infinite recursion?


What is going on that allows the rest of the loop to execute, and then for requestAnimationFrame to execute next frame?

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.

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); 
};

Solution

  • 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();
    })();
    

    Are you wondering why animloop as it is passed into requestAnimFrame doesn't cause an infinite loop when it is subsequently called?

    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.