requestAnimationFrame
A method that tells the browser you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint.
When to Use
- Animating DOM elements with JavaScript.
- Batching DOM reads and writes to prevent Layout Thrashing.
- Throttling high-frequency events (like scroll or mousemove).
When NOT to Use
- For simple animations where CSS transitions or @keyframes are sufficient.
- Executing heavy computational logic that blocks the main thread.
- For asynchronous tasks that do not involve visual updates (use setTimeout or Web Workers instead).
Advantages vs Limitations
Advantages
- Synchronizes automatically with the display refresh rate (usually 60fps).
- Pauses automatically when the user switches tabs, saving battery and CPU.
- Groups multiple DOM manipulations into a single repaint.
Limitations
- Executes strictly on the Main Thread. If the thread is blocked, rAF will be delayed (jank).
- Not suitable for exact millisecond-precise timing (unlike Web Audio API).
Production Examples
Fixing Layout Thrashing
By deferring the style mutation to the next frame, the browser avoids recalculating the layout synchronously, preserving a smooth 60fps.
// Bad: Causes synchronous layout
const w = box.offsetWidth;
box.style.width = w + 10 + 'px';
// Good: Read now, write in next frame
const w = box.offsetWidth;
requestAnimationFrame(() => {
box.style.width = w + 10 + 'px';
});Interview Readiness
Q: What is the primary difference between setTimeout and requestAnimationFrame for animations?
A: setTimeout executes arbitrarily based on the Event Loop timer, often falling out of sync with the monitor refresh rate, causing visual stutter. requestAnimationFrame is synchronized by the browser to execute immediately before the next repaint, guaranteeing smoothness and automatically pausing in inactive tabs.
Related Knowledge
Recommended Recipes
Dashboard Rendering & Layout Thrashing
Dashboards pack high-density information (charts, grids, stats) into a single view. When multiple widgets render, fetch data, and resize simultaneously, they frequently read from and write to the DOM concurrently. This triggers severe layout thrashing and jank.
Fixing DOM Layout Thrashing
Layout thrashing occurs when JavaScript alternately reads and writes to the DOM in a tight loop. Each read after a write forces the browser to immediately recalculate layout (a "reflow"), blocking the main thread. A loop of 100 elements can trigger 100 forced synchronous layouts instead of 1.