Event loop & async JavaScript

Task vs microtask queues, promises, async/await, AbortController for cancellation. "What logs first" questions are really event-loop questions.

About 28 min read3-question knowledge check

The mental model

JavaScript runs on one thread. There is exactly one call stack, so exactly one thing executes at a time — and yet a page can fetch data, animate, respond to clicks, and run timers apparently at once. The reconciling idea: the language does not do concurrency, the host (browser or Node) does. Your code hands slow work to the host — a network request, a timer, a disk read — and the host hands back a callback to run later, on that same single thread, when the work is done and the thread is free.

The event loop is the traffic controller that decides *when* "later" is. The analogy that sticks: a single chef (the thread) in a kitchen. Orders that take time — a roast in the oven, a delivery arriving — are not stood over; the chef puts a ticket in a queue and keeps cooking the quick things. The event loop is the rule the chef follows between dishes: finish the current dish completely, then clear every urgent sticky-note (microtasks), then pick up the next ticket (macrotask). It never interrupts a dish halfway. That is why "JavaScript is single-threaded but non-blocking" is not a contradiction: the thread is never split, but it is never left idle waiting either.

What breaks without this model is predictability. "What logs first?" questions are not trivia — they are asking whether you know that a resolved promise's .then runs before a setTimeout(…, 0), because microtasks drain completely before the next macrotask. A long synchronous loop freezes the entire page — clicks, scroll, animation, everything — because there is one thread and you are holding it. An await that you thought was parallel runs sequentially because you awaited inside the loop. And a fetch that keeps running after the user navigated away wastes bandwidth and can overwrite fresh state with stale, because nobody told it to stop. Each is the event loop doing exactly what it specifies while you pictured threads.

The practical payoff: once you can trace the queue, you can predict execution order, you know why the UI froze, you know where to put await, and you know that AbortController is how you cancel work the loop would otherwise finish for nothing.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision