Lesson 19 of 80
The event loop lesson introduces two queues — this one is the deep dive on the ordering puzzles interviewers actually ask, worked through step by step.
12 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
A `.then()` callback itself schedules another `.then()` callback while it runs. Does the newly-scheduled one run before or after the next `setTimeout(fn, 0)`?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
The event loop lesson covers the rule: microtasks fully drain before the next macrotask. This lesson is about actually tracing that rule through code that mixes several sources, since that's the form interview questions take.
console.log("A"); // sync
setTimeout(() => console.log("B"), 0); // macrotask
Promise.resolve().then(() => {
console.log("C");
Promise.resolve().then(() => console.log("D")); // scheduled from inside a microtask
});
console.log("E"); // sync
// Order: A, E, C, D, B
Walk it in three passes:
A, then E (the setTimeout and .then calls only schedule work, they don't run it yet).C runs, and while it runs it schedules D; since the microtask queue isn't considered empty yet, D runs too, in the same drain.B.Synchronous code runs first, top to bottom: log(1) runs, then setTimeout and .then only SCHEDULE work, then log(4) runs.
async/await follows the same rule — everything after an await is a microtask continuation, so an async function mixed with setTimeout obeys this exact ordering, not some separate async rule.queueMicrotask() schedules a microtask directly, without needing a promise at all — useful when you want "run after this task, before the next macrotask" without the promise machinery.setTimeout(fn, 0) calls still run in the order they were scheduled relative to each other — the macrotask queue is FIFO, it's only microtasks-before-macrotasks that reorders things.Tracing execution order across console.log, setTimeout, and chained .then()s is one of the highest-signal JS questions there is — it's impossible to get right by memorizing an answer, only by actually holding the two-queue model in your head.