The Event Loop

Why does a 0 ms timer print last? Follow the call stack, the promise queue and the timer queue.

JavaScript · beginner · 7 min · 8 steps · free

What you'll learn

EventLoop.js

console.log('1: start');

setTimeout(() => {
  console.log('4: timer');
}, 0);

Promise.resolve().then(() => {
  console.log('3: promise');
});

console.log('2: end');

Step by step

  1. It prints 1: start.
  2. setTimeout gives the callback to a timer. Even with 0 ms, it can only run once all the current code has finished.
  3. .then registers a callback for when the promise is ready. This promise is ready already, but the callback still waits for the script to finish.
  4. The script has finished: the call stack is empty.
  5. First the event loop runs promise callbacks (microtasks), before any timer.
  6. It prints 3: promise.
  7. Only now does the timer's callback run, though its 0 ms were up long ago.
  8. It prints 4: timer.

Common mistakes

Best practices

Key takeaways

Check yourself

Order: sync log, promise.then, setTimeout 0?

Answer: sync, promise, timeout

setTimeout(f, 0) runs f?

Answer: After the current code finishes

·

More in Asynchronous JavaScript