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.
Code
// 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
Cubic Bezier PreviewPreview a CSS cubic-bezier() easing curve, validate the control points, and sample the progress mapping from input to output value.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.