requestAnimationFrame(callback) adds the callback to the document's map of animation frame callbacks and returns a handle for cancelAnimationFrame(). It doesn't schedule a task. The callbacks run as one step of update the rendering, the work the browser does at each rendering opportunity:
- After resize and scroll events, media query changes and CSS animation events.
- Before style recalculation, layout and paint, so DOM writes made in a callback appear in that same frame.
Rules that follow from the spec's algorithm:
- One shot. Each call registers one callback for one frame. An animation loop calls
requestAnimationFrameagain from inside its callback. - Snapshot per frame. The browser takes the list of handles before running them. A callback requested during the run waits for the next frame; one cancelled during the run doesn't run.
- One timestamp per frame. Every callback receives the same
DOMHighResTimeStamp, the time of the frame's rendering opportunity on theperformance.now()clock, not the time it was called. - Microtasks between callbacks. Each callback is invoked from an empty stack, so its promise reactions run before the next callback. A callback that throws is reported, and the rest still run.
- Frame rate, not a fixed rate. Callbacks run as often as the browser renders: about every 16.7 ms at 60 Hz, possibly faster on high-refresh displays, slower when the page can't keep up.
Hidden documents are skipped by update the rendering, so the spec runs no callbacks for them. With a headless page behind another tab (visibilityState "hidden"), Chrome 156 ran none in 6 seconds; Firefox 159 still ran one every 1–2 seconds.
Use requestAnimationFrame for script-driven visual updates: canvas drawing, positions computed from input, batched DOM writes. For declarative motion, CSS animations and transitions need no per-frame script at all.