requestAnimationFrame & VSync
requestAnimationFrame (rAF) aligns JavaScript visual updates with the display's VSync cadence. Callbacks execute once per frame right before Style, Layout, and Paint, eliminating wasted intermediate renders and automatically pausing in background tabs.
Event Loop to VSync Frame Commit
Trace where requestAnimationFrame executes relative to macrotasks, microtasks, and Paint.
Display hardware signals a new frame boundary (every 16.67ms at 60Hz or 8.33ms at 120Hz).
- vsyncHz
- 60
- budgetMs
- 16.67
- phase
- BeginMainFrame
Under the Hood
Using setInterval(fn, 16) for animation is like mailing letters without checking when the postal truck leaves, some frames get two deliveries, others get zero. requestAnimationFrame hands your update directly to the driver as the truck pulls out.
- VSync Alignment: The compositor signals
BeginMainFramein sync with the monitor's refresh rate (60Hz, 120Hz, or 144Hz). - Queue Snapshotting: The Event Loop drains tasks, then runs every queued rAF callback for the current frame. Calls to
requestAnimationFramemade inside a callback defer to the next VSync. - Single Render Pass: All DOM mutations inside rAF coalesce into one pass of the Browser Rendering Pipeline.
let last = 0;
function tick(timestamp) {
const dt = last ? (timestamp - last) / 1000 : 0;
last = timestamp;
box.style.transform = `translateX(${(timestamp * 0.08) % 300}px)`;
if (dt < 1) requestAnimationFrame(tick);
}
requestAnimationFrame(tick);Problem Genealogy
- 2000–2010:
setTimeout(fn, 16)drifted out of phase with display refreshes, causing frame tearing and battery drain in hidden tabs. - 2011+: Browser vendors standardized
requestAnimationFrame, throttling background tabs to 0–1Hz and syncing foreground tabs to VSync.
Production Pitfalls
- Frame-rate-dependent speed: Incrementing
x += 2per rAF callback runs twice as fast on a 120Hz screen as on a 60Hz screen; always usetimestampdeltas. - Multiple rAF loops: Spawning independent rAF loops per component fragments main-thread timing and invites Layout Thrashing.
- When not to use
requestAnimationFrame: Do not use rAF for simpletransformoropacitytransitions; use CSS transitions, the Web Animations API, or Scroll-Driven Animations so they run off the main thread.
Connections & Logical Next Steps
Fake timers mock requestAnimationFrame at fixed 16ms intervals rather than hardware VSync signals.
WAAPI replaces manual rAF loops for imperative keyframe animations.
rAF runs in the rendering step of the HTML event loop after tasks and microtasks.
Mutations inside rAF are batched directly into the upcoming Style/Layout/Paint cycle.
rAF scroll loops sample scrollTop on the main thread, while Scroll-Driven Animations bind timelines to scroll on the compositor.