Search code examples
javascriptanimationstack-overflowframerequestanimationframe

Why requestAniamtionFrame doesn't cause stack overflow error?


I am trying to understand what happens under the hood of the browser when requestAnimationFrame() is called recursively.

I have ran code like this in my browser console:

function foo(){
    requestAnimationFrame(foo);
    console.log("foo");
}
foo()

The result: "foo" is being printend out non-stop.

My problem: I cannot figure out how I am not exceeding allowed stack size.

What I think is happening:

function callAsynchronously(callback){
    setTimeout(callback, 1);
}

function foobar(){
    callAsynchronously(foobar); // replacement for requestAnimationFrame
    console.log("hi");
}

foobar() // result is the same as before, non-stop printing

Above code is how I am visualizing requestAnimationFrame:

  1. foobar() is put on the stack
  2. callAsynchronously(foobar) is put on stack
  3. callAsynchronously(foobar) popped from the stack
  4. console.log("hi") is put on stack / browser apis put foobar callback into some queue after setTimeout is finished
  5. console.log("hi") is popped from the stack
  6. browser sees empty stack and puts callback from the queue on the stack
  7. Repeat

I assume that requestAnimationFrame does something similar to not exceed allowed stack size but I am not sure if that's all there is to it. Also does it mean that I can bombard browser apis with async callbacks without getting any errors as long as I keep my stack size within acceptable range?


Solution

  • requestAnimationFrame doesn't run until all synchronous execution has completed. It schedules the given callback. It acts very much like setTimeout. Its not truly recursive, it just seems that way. Thats the nature of the event loop.