Facebook Pixel

setTimeout vs requestAnimationFrame vs queueMicrotask in JavaScript

Three scheduling APIs with different priorities. Here is when to use each.

setTimeout vs requestAnimationFrame vs queueMicrotask in JavaScript

JavaScript has several scheduling APIs. Each has a different priority and use case.

setTimeout (Macrotask)

  • Queue: macrotask queue.
  • Priority: lowest (runs after microtasks and rendering).
  • Use case: delayed actions, breaking long tasks, polling.

requestAnimationFrame (Before Paint)

  • Queue: runs before the next paint.
  • Priority: between microtasks and macrotasks.
  • Use case: visual animations, DOM updates.

queueMicrotask (Microtask)

  • Queue: microtask queue.
  • Priority: highest (runs before rendering and macrotasks).
  • Use case: urgent work that should run before the next event.

Order of Execution

console.log("sync"); setTimeout(() => console.log("timeout"), 0); requestAnimationFrame(() => console.log("rAF")); queueMicrotask(() => console.log("microtask"));

Output: sync, microtask, rAF, timeout.

The Takeaway

setTimeout is a macrotask (lowest priority). requestAnimationFrame runs before the next paint (for animations). queueMicrotask is a microtask (highest priority). Use each for its specific use case.

setTimeout is a macrotask (lowest priority, runs after rendering). requestAnimationFrame runs before the next paint (for animations). queueMicrotask is a microtask (highest priority, runs before rendering and macrotasks).

For animations and visual DOM updates. requestAnimationFrame syncs with the browser's refresh rate (usually 60fps), runs before the next paint, and produces smoother animations than setTimeout.

For urgent work that must run before the next event or paint. queueMicrotask adds the callback to the microtask queue, which the event loop drains before rendering and macrotasks.

Sync code runs first. Then microtasks (queueMicrotask, Promise.then). Then requestAnimationFrame (before the next paint). Then setTimeout (macrotask, after rendering).

A callback that runs when the browser is idle (between frames). The deadline object tells you how much time is left. Useful for low-priority work that should not cause frame drops.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.