Skip to content
jshacks.dev
Fundamentals

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.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js, Vite and npm logos.

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.

JavaScript
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");
Text
script start
async function runs synchronously
script end
microtask: promise
microtask: queueMicrotask
microtask: after await
task: setTimeout

All 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

SourceRuns as a microtask
promise.then(fn) on a settled promisefn, when the promise settles or at once if it already has
promise.catch(fn), promise.finally(fn)fn, in the same way
Code after awaitThe continuation of the async function
queueMicrotask(fn)fn
MutationObserver callbacks, in browsersThe 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.

JavaScript
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"));
Text
chain 1, step 1
chain 2, step 1
chain 1, step 2
chain 2, step 2
chain 1, step 3

Each 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.

JavaScript
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"));
Text
A1
B1
B2
B3
A2
B4

Chain 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.

JavaScript
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");
Text
task: before await
sync end
task: after first await
then 1
task: after second await
then 2
then 3

The 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.

JavaScript
setTimeout(() => {
  console.log("timer 1");
  Promise.resolve().then(() => console.log("microtask from timer 1"));
}, 0);

setTimeout(() => console.log("timer 2"), 0);
Text
timer 1
microtask from timer 1
timer 2

Both 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.

JavaScript
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);
Text
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.

JavaScript
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);
  }
});
Text
caught inside: in queueMicrotask
caught: in a then callback

The 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.

  • "async functions are asynchronous from the first line." The body runs synchronously until the first await.

A mistake we hit: assuming the order of two independent chains

JavaScript
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);
Text
[ '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 wantUse
Run right after the current code, before any timerqueueMicrotask(fn) or a promise callback
Combine several changes into one updateA flag and queueMicrotask
Run after rendering or I/OsetTimeout, setImmediate or requestAnimationFrame
Wait for an async operationawait
Control order between chainsChain 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.

Taggedinterview
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.