Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 666
Yad Smood Avatar asked Jul 29 '13 14:07

Yad Smood


People also ask

Why is requestAnimationFrame better than setInterval or setTimeout?

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.

Is requestAnimationFrame blocked?

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.

Is requestAnimationFrame recursive?

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.


1 Answers

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.

like image 127
Joe Avatar answered Nov 14 '22 22:11

Joe