Rendering PipelineBaseline · Widely

requestAnimationFrame & VSync

Mental Model

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.

Interactive Simulator

Event Loop to VSync Frame Commit

Trace where requestAnimationFrame executes relative to macrotasks, microtasks, and Paint.

VSync
rAF Queue
Style/Layout/Paint
Commit
Step 1 / 3: 1. VSync Pulse Arrives

Display hardware signals a new frame boundary (every 16.67ms at 60Hz or 8.33ms at 120Hz).

Internal State / Memory
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.

  1. VSync Alignment: The compositor signals BeginMainFrame in sync with the monitor's refresh rate (60Hz, 120Hz, or 144Hz).
  2. Queue Snapshotting: The Event Loop drains tasks, then runs every queued rAF callback for the current frame. Calls to requestAnimationFrame made inside a callback defer to the next VSync.
  3. Single Render Pass: All DOM mutations inside rAF coalesce into one pass of the Browser Rendering Pipeline.
JS
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

Production Pitfall
  • Frame-rate-dependent speed: Incrementing x += 2 per rAF callback runs twice as fast on a 120Hz screen as on a 60Hz screen; always use timestamp deltas.
  • Multiple rAF loops: Spawning independent rAF loops per component fragments main-thread timing and invites Layout Thrashing.
When Not to Use
  • When not to use requestAnimationFrame: Do not use rAF for simple transform or opacity transitions; use CSS transitions, the Web Animations API, or Scroll-Driven Animations so they run off the main thread.

Connections & Logical Next Steps

Mechanical Comparisons