Search code examples
javascriptgoogle-chromev8

Why "requestAnimationFrame" recursion won't eat up RAM?


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

Solution

  • 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.