CodePark/ questions / Event loop
START PRACTICINGPRACTICE
Frontend question · JavaScript › Event loop

Explain the JavaScript event loop.

The event loop is how JavaScript runs one piece of code at a time on a single thread, while waiting work happens in the background.

JavaScript runs your code on one thread with one call stack. The host environment (the browser or Node) handles slow or waiting work, such as timers, network calls, file I/O and user events. When that work is done, the host puts a callback in a queue.

The event loop repeats these steps:

  • Take the oldest task from the task queue (also called the macrotask queue). Run it until the call stack is empty.
  • Run every microtask in the microtask queue, until it is empty. This includes microtasks added by other microtasks.
  • In browsers, the page may now render (redraw the screen).
  • Pick the next task.

Tasks include the initial script, setTimeout and setInterval callbacks, and UI and I/O events.

Microtasks include promise reactions (then, catch, finally, and the code after await), queueMicrotask and MutationObserver.

Nothing can interrupt code that is running. So a long synchronous loop blocks clicks, rendering and timers until it ends.

  • JavaScript has a single thread and one call stack. The host does the async work.
  • The loop runs one macrotask (task) at a time, until it completes.
  • The microtask queue is fully emptied after each task, before rendering.
  • Promise callbacks are microtasks. Timers and events are tasks.
  • Blocking the call stack freezes the UI.