Sikau

Advanced JavaScript · Day 18 · about 30 min

The event loop

Tasks, microtasks and who goes first.

One cook, many orders

JavaScript runs one thing at a time. So how do timers, clicks and promises all get handled? The event loop: a cook who finishes the current dish, then picks the next order from the queues — in a strict order.

The order of things

  • Run all the current (synchronous) code to the end.
  • Run every queued microtask — promise callbacks (.then, await continuations, queueMicrotask).
  • Run one task — like a setTimeout callback or a click handler.
  • Repeat from step 2.
console.log("1 sync");
setTimeout(() => console.log("4 timeout (task)"), 0);
Promise.resolve().then(() => console.log("3 promise (microtask)"));
console.log("2 sync");

VIP lane: Microtasks are the VIP lane: after every dish, the cook serves the entire VIP lane before taking even one regular order.

The rest of this lesson

  • await is a microtask tooexplain
  • Why the order matters in practiceexplain
  • Predict the orderpredict
  • Sync, micro, macropredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 27 lessons of Advanced JavaScript