requestAnimationFrame(cb) runs cb once, right before the browser's next rendering update, at the display's refresh rate (60, 120 Hz…), and is paused in hidden tabs. Use it for visual updates such as JS-driven animation, canvas drawing and batched DOM writes. requestIdleCallback(cb, { timeout }) runs cb when the browser has spare time in a frame, passing a deadline you must respect. Use it for non-urgent background work such as analytics, prefetching and cache warming. setTimeout queues an ordinary task after a minimum delay. It isn't aligned with frames, and is clamped and throttled.
task → microtasks → [rendering opportunity:
resize/scroll events → rAF callbacks → style → layout → paint ]
→ idle period (rIC callbacks if time remains before next frame)
requestAnimationFrame | requestIdleCallback | setTimeout(fn, 0) | |
|---|---|---|---|
| Runs | Before the next paint | In idle periods (≤ 50 ms slices) | As a task after ≥ delay |
| Frequency | Once per frame per request | When idle; may be postponed indefinitely without timeout | Once |
| Background tab | Paused | Throttled heavily | Throttled (≥ 1 s, longer under intensive throttling) |
| Good for | Visual updates, measuring then mutating DOM | Low-priority, chunkable work | Yielding, deferring |
| Not good for | Heavy computation (blocks the frame) | DOM changes (they force extra layout in the next frame), anything urgent | Smooth animation |
// rAF animation loop with time-based movement (refresh-rate independent)
let last;
function step(now) {
const dt = last ? now - last : 0;
last = now;
x += speed * dt;
box.style.transform = `translateX(${x}px)`;
if (x < 500) requestAnimationFrame(step);
}
requestAnimationFrame(step);
// rIC: process a queue in idle slices, with a guarantee it eventually runs
function drain(deadline) {
while (queue.length && deadline.timeRemaining() > 2) send(queue.shift());
if (queue.length) requestIdleCallback(drain, { timeout: 2000 });
}
requestIdleCallback(drain, { timeout: 2000 });
Key details:
deadline.didTimeout tells you the callback ran because of the timeout, not idleness. Do minimal work then.requestIdleCallback has historically been missing in Safari, so feature-detect and fall back (setTimeout with a small delay). The polyfill can't truly detect idleness.scheduler.postTask(fn, { priority: 'background' }) is a more general prioritised alternative where supported. scheduler.yield() is for breaking up long tasks.rAF(() => rAF(fn))) to "wait for paint". They work, but scheduler.yield() or a well-placed rAF + setTimeout is clearer.timeout, Safari support, and scheduler.postTask as the modern alternative.Spotted a mistake or a rights concern? Report an issue