Skip to the solution
MediumPhone Screen8 min read

What does queueMicrotask() do, and how does its callback ordering compare to a resolved Promise .then() and setTimeout(fn, 0)?

499 views

The problem

Question presented to candidate: "Say I call queueMicrotask, then Promise.resolve().then, then setTimeout with a delay of 0, in that exact order. What order do the three callbacks actually run in, and why?"

What a strong answer should cover:

  • queueMicrotask() schedules a callback on the SAME microtask queue that Promise .then callbacks use -- it is not a separate, lower-priority queue.
  • setTimeout(fn, 0) schedules a macrotask, which never runs until the current microtask queue is completely empty, no matter how many more microtasks get added along the way.
  • Ordering among microtasks follows scheduling order (FIFO), not API identity -- whichever of queueMicrotask or .then was scheduled first runs first.
  • A microtask that itself schedules another microtask (including a nested queueMicrotask call) still runs before the next macrotask, because the engine keeps draining the microtask queue until it is genuinely empty.
  • Real motivation for queueMicrotask existing: it lets code schedule microtask-timed work without allocating a throwaway Promise just to get access to .then.

Clarifying questions expected:

  • "Is this the browser event loop or the Node.js event loop specifically -- Node has an extra process.nextTick queue that runs even earlier than both."

Code / implementation expected: Yes -- a short, runnable snippet demonstrating the actual print order.

  • event-loop
  • microtask
  • queuemicrotask

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

8 min read Β· 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptMicrotask vs macrotask ordering, including a nested microtask (run directly)

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 89 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What is the prototype chain?

Continue