JavaScript Interview Question Explain Microtasks in Depth
How to answer the microtasks question: a queue of small jobs from promises and queueMicrotask that runs to empty after each task. See tick counts and batching.

Microtasks are the part of the event loop that interviewers use to separate candidates who have read about asynchronous JavaScript from candidates who can predict what a tricky snippet prints. The general event loop answer, covered in the event loop question, says microtasks run before the next task. The microtask question goes one level deeper: what exactly creates them, how many "ticks" different operations take, why returning a promise from a then callback changes the order, and when you would schedule one on purpose. This post gives the answer in thirty seconds, then the sources of microtasks, the interleaving rule with an exact output, the extra ticks that thenables cost, the checkpoint between tasks, a practical batching pattern, and the wrong answers to avoid. The examples run on Node.js 24 as ES modules.
The answer in thirty seconds
A microtask is a small job queued to run as soon as the current JavaScript finishes, before the engine returns to the event loop for the next task. Promise reactions, which are the callbacks of then, catch and finally, are microtasks, as is the code that continues after an await, and anything passed to queueMicrotask(). The microtask queue is first in, first out, and it is drained completely: microtasks that are queued by other microtasks run in the same drain, so the queue empties before any timer, input event or I/O callback gets a turn.
console.log("script start");
setTimeout(() => console.log("task: setTimeout"), 0);
Promise.resolve().then(() => console.log("microtask: promise"));
queueMicrotask(() => console.log("microtask: queueMicrotask"));
(async () => {
console.log("async function runs synchronously");
await null;
console.log("microtask: after await");
})();
console.log("script end");script start
async function runs synchronously
script end
microtask: promise
microtask: queueMicrotask
microtask: after await
task: setTimeoutAll the synchronous lines come first, including the start of the async function, which runs until its first await. Then the three microtasks run in the order they were queued, and only after that does the timer fire. Writing the output of this snippet correctly is the core of the answer.
What creates a microtask
| Source | Runs as a microtask |
|---|---|
promise.then(fn) on a settled promise | fn, when the promise settles or at once if it already has |
promise.catch(fn), promise.finally(fn) | fn, in the same way |
Code after await | The continuation of the async function |
queueMicrotask(fn) | fn |
MutationObserver callbacks, in browsers | The observer callback, batched |
Not microtasks: setTimeout, setInterval and setImmediate, I/O callbacks, and DOM events, which are all tasks. The executor passed to new Promise is also not a microtask, since it runs synchronously, as the first line of the next example shows.
The interleaving rule
Two independent promise chains advance one step per round, alternating.
Promise.resolve()
.then(() => console.log("chain 1, step 1"))
.then(() => console.log("chain 1, step 2"))
.then(() => console.log("chain 1, step 3"));
Promise.resolve()
.then(() => console.log("chain 2, step 1"))
.then(() => console.log("chain 2, step 2"));chain 1, step 1
chain 2, step 1
chain 1, step 2
chain 2, step 2
chain 1, step 3Each then callback runs in a microtask, and when it finishes, it queues the next step of its own chain at the back of the queue. The two chains take turns, because the second chain's first step is already waiting behind the first chain's first step. This interleaving is what interviewers draw on the board: a queue with the next callbacks of each chain in order. The rule behind it is that a step costs one tick, where a tick is one trip through the queue.
Returning a promise costs extra ticks
A then callback that returns a promise makes the chain wait for it, and the waiting is not free.
Promise.resolve()
.then(() => {
console.log("A1");
return Promise.resolve();
})
.then(() => console.log("A2"));
Promise.resolve()
.then(() => console.log("B1"))
.then(() => console.log("B2"))
.then(() => console.log("B3"))
.then(() => console.log("B4"));A1
B1
B2
B3
A2
B4Chain A returned a promise from its first step, and its second step ran only after chain B had completed three steps. Resolving a promise with another promise takes two extra ticks: the engine queues a job to attach to the returned promise, that job queues the reaction, and only then is the outer promise resolved, which queues the next then. Had A1 returned a plain value, A2 would have run on the second tick, between B1 and B2. This is the puzzle that surprises most candidates, and the explanation is worth learning: returning a promise is slower than returning a value, by two ticks.
await and ticks
An await on a native promise costs one tick, so the continuation interleaves with then chains.
async function task() {
console.log("task: before await");
await undefined;
console.log("task: after first await");
await undefined;
console.log("task: after second await");
}
task();
Promise.resolve()
.then(() => console.log("then 1"))
.then(() => console.log("then 2"))
.then(() => console.log("then 3"));
console.log("sync end");task: before await
sync end
task: after first await
then 1
task: after second await
then 2
then 3The async function and the promise chain take turns: the first continuation of task was queued before the first then, so it runs first, and each later step follows the same one-tick rhythm. In engines before 2019, an await cost three ticks, and the output order was different. The current behavior is part of the specification, so you can rely on it, and it is a good detail to mention in an interview.
The checkpoint between tasks
The queue is drained after each task, not once per loop.
setTimeout(() => {
console.log("timer 1");
Promise.resolve().then(() => console.log("microtask from timer 1"));
}, 0);
setTimeout(() => console.log("timer 2"), 0);timer 1
microtask from timer 1
timer 2Both timers were due at the same time, and the microtask that timer 1 queued ran before timer 2. That is the behavior in browsers and in Node.js 11 and later. In older Node.js versions, both timers ran first, and the microtask came after, which is a historical difference that still appears in interview questions. The general rule is that after any callback finishes and the stack is empty, the engine drains the microtask queue before it runs another callback.
A practical use: batching updates
Because a microtask runs after the current code but before the next task, it is the right tool for combining several changes into one piece of work.
const pending = [];
let scheduled = false;
function update(change) {
pending.push(change);
if (!scheduled) {
scheduled = true;
queueMicrotask(flush);
}
}
function flush() {
scheduled = false;
console.log("flush with", pending.splice(0));
}
update("a");
update("b");
update("c");
console.log("updates queued");
setTimeout(() => {
update("d");
}, 0);updates queued
flush with [ 'a', 'b', 'c' ]
flush with [ 'd' ]Three calls in the same turn produced one flush with all three changes. The flag stops a second microtask from being queued. After the timer, the fourth update starts a new batch. This is how many front end libraries batch state changes, and it is the interview answer to "when would you use queueMicrotask": to run something right after the current code, once, without waiting for a timer.
Exceptions in microtasks
An error thrown in a promise callback rejects the promise, and an error in a queueMicrotask callback is not caught by anything.
Promise.resolve()
.then(() => {
throw new Error("in a then callback");
})
.catch((error) => console.log("caught:", error.message));
queueMicrotask(() => {
try {
throw new Error("in queueMicrotask");
} catch (error) {
console.log("caught inside:", error.message);
}
});caught inside: in queueMicrotask
caught: in a then callbackThe promise machinery turns a thrown error into a rejection that catch handles, so the then callback's error reached the handler. A queueMicrotask callback has no promise around it: an uncaught error there is reported as an uncaught exception, which crashes a Node.js process by default. Wrap the body in try and catch, as the example does. The ordering of the two lines is the same one-tick rule: the catch handler runs one tick after the then callback that rejected, and the microtask ran in between.
Starvation
Because the queue is drained completely, microtasks that keep queuing more microtasks starve everything else. This was shown in the event loop question with a loop, and the lesson for microtasks is the same: a promise chain without an end, or a recursive queueMicrotask, blocks timers, input and rendering, since the next task never starts. A break in the chain with a real task, such as setTimeout, gives the loop its turn.
Wrong answers that lose the point
"Microtasks run in parallel with the main code." They run on the same thread, after the current code ends.
"A promise callback runs immediately if the promise is already resolved." It is always queued, never run synchronously.
"Microtasks and tasks are the same queue." They are separate, and microtasks have priority.
"
asyncfunctions are asynchronous from the first line." The body runs synchronously until the firstawait.
A mistake we hit: assuming the order of two independent chains
const log = [];
const slow = Promise.resolve()
.then(() => Promise.resolve())
.then(() => log.push("slow"));
const fast = Promise.resolve().then(() => log.push("fast"));
await Promise.all([fast, slow]);
console.log(log);
const first = new Promise((resolve) => resolve("first"));
const second = Promise.resolve("second");
const seen = [];
first.then((value) => seen.push(value));
second.then((value) => seen.push(value));
await null;
console.log(seen);[ 'fast', 'slow' ]
[ 'first', 'second' ]The first pair shows that a callback attached to a promise returned from another then waits longer, so fast is logged first although slow was created first. We had code that relied on two independent chains finishing in the order they were written, and it worked until someone added a promise return in one of them. The second pair shows the stable part: callbacks attached to settled promises run in attachment order. If order matters between chains, make it explicit by chaining them or by awaiting one before starting the other.
Choosing between the scheduling tools
| You want | Use |
|---|---|
| Run right after the current code, before any timer | queueMicrotask(fn) or a promise callback |
| Combine several changes into one update | A flag and queueMicrotask |
| Run after rendering or I/O | setTimeout, setImmediate or requestAnimationFrame |
| Wait for an async operation | await |
| Control order between chains | Chain them with then, or await in sequence |
Practical rules we follow
Do not rely on the tick counts of different chains: chain them when order matters. Avoid returning promises from then callbacks in code where order is delicate, and prefer await. Wrap queueMicrotask bodies in try. Never write an unbounded microtask loop. Use a microtask to batch and a task to yield. And when predicting output, write the queue after each step.
Where the microtasks answer stops being enough
A deeper question covers the promise resolution procedure and thenables, the exact tick counts of Promise.all and Promise.race, the HTML specification's definition of a microtask checkpoint, and how process.nextTick fits in Node.js. The answer above covers the working model. The reference is in the MDN microtask guide and the HTML specification on microtask queueing.


