Request Animation Frame Render Loop

Schedule paint-aligned work with requestAnimationFrame, cancel pending callbacks before the next frame, and count the frames that actually ran.

JavascriptData Fetching

Code

javascriptsnippet
16 lines
// requestAnimationFrame 安排下一次绘制前执行的回调
const meter = document.querySelector('#meter');

if (meter) {
  let frames = 0;
  const render = () => {
    frames += 1;
    meter.textContent = `frame ${frames}`;
    if (frames < 60) requestAnimationFrame(render);
  };

  const pending = requestAnimationFrame(render);
  // 下一帧到来之前取消:回调一次都不会执行
  cancelAnimationFrame(pending);
  requestAnimationFrame(() => console.log('frames rendered:', frames));
}

How the snippet works

Count the function render as the entire surface area of Request Animation Frame Render Loop.

What to watch for

  • Uses document, requestAnimationFrame, so it needs a browser context — it will not run as-is in Node without shims.

Using it

The main signature reads const render = ()

Output lines are prefixed (frames rendered:), making each step’s effect easy to spot.

Key statements

const render = () => {
frames += 1;
meter.textContent = `frame ${frames}`;
if (frames < 60) requestAnimationFrame(render);
};

Interactive Tools for This Topic

FAQ

Does Request Animation Frame Render Loop run in plain Node.js?
No — it touches `document` and `requestAnimationFrame`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.