Dmytro Morar
JavaScript

Event Loop

The Event Loop is a mechanism that controls the order of code execution in JavaScript. It allows single-threaded JS to process asynchronous tasks, ensuring continuous program execution without blocking.

Core Idea

  • JavaScript works in one thread, where the call stack (Call Stack) is executed.
  • Asynchronous operations (timers, I/O, promises) are handled by external APIs of the environment (browser, Node.js).
  • Upon completion, the operation adds a callback to the corresponding task queue.
  • The Event Loop monitors the stack: when it is empty, it takes a task from the queue and places it in the stack for execution.

Execution Order and Priority

  1. All synchronous code (code in the call stack) is executed.
  2. When the stack is empty, the Event Loop takes one macrotask from the queue and executes it.
  3. After that, all microtasks are executed (the queue is cleared completely).
  4. Then the browser can perform frame rendering.
  5. The cycle repeats.

If new microtasks are created during the execution of microtasks — they are also executed in the same pass until the queue is empty.

Microtasks

  • Promise.then, .catch, .finally
  • queueMicrotask()
  • MutationObserver
  • (Node.js) process.nextTick() — executed earlier than regular microtasks

Macrotasks

  • setTimeout, setInterval
  • setImmediate (Node.js)
  • postMessage, MessageChannel
  • DOM event callbacks
  • requestAnimationFrame — called between microtask clearing and frame rendering, formally does not belong to any category.

Microtask vs Macrotask

CharacteristicMicrotaskMacrotask
ExamplesPromise.then, queueMicrotask, MutationObserversetTimeout, setInterval, DOM events
SourceInternal JS APIsExternal environment APIs (browser / Node.js)
PriorityExecuted immediately after the current task, before renderingExecuted one per iteration of the Event Loop
UsageShort operations requiring immediate processingAsynchronous operations, timers, events
SequenceAll microtasks are executed before the next macrotaskAfter clearing microtasks and possible rendering

In other words, microtasks are executed earlier than macrotasks — they create an internal priority cycle within one step of the Event Loop.

Key Ideas

  • The Event Loop coordinates the execution of synchronous and asynchronous code.
  • Microtasks are always executed before the next macrotask.
  • Promises and timers fall into different queues and are processed at different stages of the cycle.
  • This mechanism guarantees smooth, non-blocking operation of JS applications.

Links

On this page