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
:
foobar()
is put on the stackcallAsynchronously(foobar)
is put on stackcallAsynchronously(foobar)
popped from the stackconsole.log("hi")
is put on stack / browser apis putfoobar
callback into some queue aftersetTimeout
is finishedconsole.log("hi")
is popped from the stack- browser sees empty stack and puts callback from the queue on the stack
- 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?
Comments
Post a Comment