Codectionary / Developer documentation / JavaScript

Microtasks and Event-loop Ordering

queueMicrotask schedules work after the current JavaScript stack finishes, before the event loop proceeds to another task. Promise reactions also use microtasks. Recursively queuing microtasks can delay rendering and timers indefinitely, so this queue is for short follow-up work.

Syntax

queueMicrotask(() => console.log("after current stack"));

Examples

Microtasks and Event-loop Ordering: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: Logs appear in order: start, end, microtask, promise, timer.

console.log("start");
setTimeout(() => console.log("timer"), 0);
queueMicrotask(() => console.log("microtask"));
Promise.resolve().then(() => console.log("promise"));
console.log("end");
  1. Expected result: Logs appear in order: start, end, microtask, promise, timer.
  2. Synchronous statements finish before either queued microtask.
  3. The two microtasks run in the order they were queued, before the timer task.

Best practices

  • Keep microtasks short and bounded.
  • Use a timer or another task-yielding mechanism when work should let the browser process other tasks.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading