What does queueMicrotask() do?
Definition
javascript
queueMicrotask(callback)What it does:
- Adds the
callbackfunction 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
BWhy?
- First, all synchronous code runs (
A, thenC); - 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
- The current code (on the Call Stack) runs to completion;
- Once it finishes, the Event Loop checks the microtask queue;
- All microtasks in the queue run in order;
- 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
timeoutOrder:
sync- synchronous code,microtask- microtask queue,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
B2. 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
| Property | Value |
|---|---|
| What it does | Adds a function to the microtask queue |
| When it runs | After the current code, but before any macrotasks |
| Equivalent | Promise.resolve().then(fn) |
| Queue | Microtask Queue |
| Return value | undefined |
| Use | A lightweight, fast alternative to promises for microtasks |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.