As the title, why the requestAnimationFrame
recursion won't eat up RAM. This post said that the V8 engine has no optimization for the tail call
, so I think I must have missed something. Is that because the browser did something behind it? Or the V8 supports the optimization of tail call
?
Here's the MDN's example:
function step(timestamp) {
var progress = timestamp - start;
d.style.left = Math.min(progress/10, 200) + "px";
if (progress < 2000) {
requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
The reason for this is because you must re-call requestAnimationFrame inside your function to queue up the next time the function will be called. Unlike setInterval , requestAnimationFrame will only continue to call the same function if you tell it to.
Animations with requestAnimationFrame are non-blocking, which means if you make subsequent calls to requestAnimationFrame, the resulting animations will all occur at same time. The goal is 60 frame per second(fps) to appear smooth animation.
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.
requestAnimationFrame
notifies the browser that it wants the callback function to be executed as soon as a frame needs drawing. The closure of the function must be stored until the callback is made, but after that it can be garbage collected, providing it is not referenced elsewhere.
There is no recursion here, as we are going via an event loop which disconnects the execution. The function is not calling itself, it is asking to be called. Every time it finishes executing, that bit of RAM can be reclaimed.
Worth remembering that if step
simply called itself, that would be an infinite recursion. In this case, the stack would blow up. If we imagine an infinite stack that can't blow up (or tail-call recursion), it would block the event loop and prevent any other code from running, as only one function can run at once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With