最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why "requestAnimationFrame" recursion won't eat up RAM? - Stack Overflow

programmeradmin1浏览0评论

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

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);
Share Improve this question edited May 23, 2017 at 12:22 CommunityBot 11 silver badge asked Jul 29, 2013 at 14:12 Yad SmoodYad Smood 2,9422 gold badges26 silver badges38 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15

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.

发布评论

评论列表(0)

  1. 暂无评论