Skip to main content

What does queueMicrotask() do?

Definition

javascript
queueMicrotask(callback)

What it does:

  • Adds the callback function to the microtask queue;
  • It runs after the current function finishes, but before any setTimeout, setInterval, events, or other macrotasks.

Example

javascript
console.log('A'); queueMicrotask(() => console.log('B')); console.log('C');

Output:

javascript
A C B

Why?

  • First, all synchronous code runs (A, then C);
  • Then the Event Loop sees that the stack is empty and runs the microtask (B) before moving on to macrotasks.

What happens under the hood

  1. The current code (on the Call Stack) runs to completion;
  2. Once it finishes, the Event Loop checks the microtask queue;
  3. All microtasks in the queue run in order;
  4. Only then does it take the next macrotask (for example, setTimeout).

Comparison with Promise.then

queueMicrotask() works the same way as Promise.resolve().then(callback), but without creating a Promise object, which makes it slightly faster and simpler.

Example - equivalent code:

javascript
Promise.resolve().then(() => console.log('microtask via Promise')); queueMicrotask(() => console.log('microtask via queueMicrotask'));

Both functions go into the microtask queue and run before any timers.

Example with a timer

javascript
setTimeout(() => console.log('timeout'), 0); queueMicrotask(() => console.log('microtask')); console.log('sync');

Output:

javascript
sync microtask timeout

Order:

  1. sync - synchronous code,
  2. microtask - microtask queue,
  3. timeout - macrotask queue.

Important to know

1. All microtasks run one after another

If a new microtask is created inside a microtask, it gets added to the queue and runs before moving on to a macrotask.

javascript
queueMicrotask(() => { console.log('A'); queueMicrotask(() => console.log('B')); });

Output:

javascript
A B

2. You can "hang" the loop with infinite scheduling

javascript
function loop() { queueMicrotask(loop); } loop();

Code like this "hangs" the Event Loop: microtasks keep running forever, and no macrotask (setTimeout, clicks, and so on) ever gets to run.

3. Supported everywhere

queueMicrotask() is an ECMAScript 2019 standard, and it is supported by all modern browsers and Node.js.

Summary

PropertyValue
What it doesAdds a function to the microtask queue
When it runsAfter the current code, but before any macrotasks
EquivalentPromise.resolve().then(fn)
QueueMicrotask Queue
Return valueundefined
UseA lightweight, fast alternative to promises for microtasks

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.