JavaScript · Question 97
When should browser UI code use requestAnimationFrame(), microtasks, or timers?
Direct answer
Use microtasks for short ordering-sensitive follow-up before returning control to later tasks, requestAnimationFrame() for visual updates coordinated with an upcoming rendering opportunity, and timers for task scheduling after at least a delay—not for precise frame synchronization.
A microtask scheduled with queueMicrotask() runs during a microtask checkpoint and can occur before the browser gets another rendering opportunity. That makes microtasks excellent for normalizing ordering, but a poor mechanism for repeatedly performing heavy visual work.
A requestAnimationFrame() callback is specifically associated with browser rendering opportunities and is therefore the natural place to calculate or apply animation-frame updates. A setTimeout() callback is a later task subject to delay clamping and scheduling conditions; a delay of zero never means “immediately” or “exactly before the next paint.”
- Ordering cleanup or deferred notification within the same turn → microtask.
- Per-frame visual update →
requestAnimationFrame(). - Run later after a delay or yield into a later task → timer/task-oriented scheduling, while accepting timing is not exact.