02 · Event Loop & Asynchronous JavaScript
mediumpredictionjavascript~8 min

Predict Promise and setTimeout Order

Objective: Order synchronous code, microtasks (in queue order) and macrotasks.

Predict the exact order of the logs, mixing synchronous code, a timer, promise callbacks and an async function.

  • Write one value per line, in print order.
Read the code, then type what it prints
console.log("1");

setTimeout(() => console.log("2"), 0);

Promise.resolve().then(() => console.log("3"));

(async () => {
  console.log("4");
  await null;
  console.log("5");
})();

queueMicrotask(() => console.log("6"));

console.log("7");
Output
> Nothing has run yet.
Interview follow-up questions
  • What changes if the `await null` becomes `await somePromise` that is already resolved?
  • Can microtasks starve the event loop? How?
  • How does this differ in Node.js (process.nextTick)?