Skip to the solution
HardFrontend6 min read

In what order do console.log, setTimeout, and Promise.then run?

775 views

The problem

Question presented to candidate: "If I mix several console.log calls with a couple of setTimeout(fn, 0) calls and a couple of Promise.then calls, in what exact order do they all print, and why?"

What a strong answer should cover:

  • Every synchronous console.log runs first, in the exact order it appears in the source -- before any queued callback runs at all.
  • After the synchronous code finishes, the ENTIRE microtask queue drains -- every Promise.then callback runs, in the order those callbacks were actually scheduled, not the order the .then() calls appear if scheduling happens indirectly.
  • setTimeout callbacks run only after the whole microtask queue reports empty, and among themselves, they run in the order they were scheduled.
  • A chained .then() (a second .then() attached to the result of the first) is scheduled ONLY once the first .then() callback actually runs -- so a two-deep chain takes two full microtask-queue passes, not one.
  • This is not a memorized fact -- it follows directly from two queues (microtask, macrotask) and one rule: the microtask queue always fully drains before the next macrotask runs.

Clarifying questions expected:

  • "Should I also cover process.nextTick, or keep this to the standard browser-style microtask/macrotask model?"

Code / implementation expected: Yes -- a short, runnable snippet mixing synchronous logs, a chained .then(), a separate .then(), and two setTimeout calls, with the real observed order.

  • event-loop
  • order

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

6 min read Β· 7 sections

Run the code

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

JavaScriptMixed sync logs, chained then, separate then, two setTimeouts (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 135 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 nextHard

Explain how prototypal inheritance differs from classical inheritance.

Continue