JavaScriptworking

How does the JavaScript event loop order a promise and a timeout?

Trace the call stack, then microtasks, then the next macrotask.

Points worth saying

  • JavaScript runs one call stack. Timers and promises wait off that stack.
  • Promise callbacks are microtasks. They run before the next timer.
  • A long synchronous loop blocks both, no matter which one was scheduled first.

A full answer

The engine runs the current stack to completion. setTimeout schedules a macrotask. A resolved promise schedules a microtask. When the stack is empty, the loop drains the microtask queue before it takes the next macrotask.

That is why a promise callback runs before a timeout of zero milliseconds, even if the timeout was registered first. Zero does not mean “now.” It means “after the current stack and the microtasks that are already queued.”

Microtasks can queue more microtasks. A promise that resolves another promise will keep the loop in the microtask queue until that chain settles. A timer scheduled from inside that chain still waits.

The failure mode interviewers want is a blocking loop. A tight for-loop on the main thread does not yield. Timers, clicks, and promise callbacks all wait until it returns. Move long work off the critical path, or break it up so the loop can breathe.

Mark your progress

Create a practice profile to mark this question.