AceDevHub
Intermediate JavaScript Interview QuestionsIntermediateCode Output

JavaScript · Question 46

What is the output order when synchronous code, Promise callbacks, and setTimeout(0) are mixed?

Direct answer

Synchronous logs run first, then queued Promise microtasks, then the timer task in a later event-loop turn.

event-loop-order.js
console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
Output
A
D
C
B

For console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');, the common browser/host ordering is A, D, C, B.

  • A prints during the current synchronous execution.
  • The timer callback is scheduled for a future task.
  • Promise.then() schedules a Promise reaction job that the host processes as a microtask.
  • D prints before the current stack finishes.
  • At the microtask checkpoint, C runs before the event loop takes the timer task that prints B.

A stronger interview follow-up is to add another Promise.then() inside the first microtask. That new microtask is normally processed in the same checkpoint before the event loop advances to the timer task.