Skip to main content
JavaScript3 min read

Understanding the JavaScript Event Loop and Asynchronous Execution

A deep dive into how the JavaScript runtime handles concurrency, the call stack, microtasks, and macrotasks.

JavaScriptEvent LoopAsynchronousNode.js

Introduction to the Single-Threaded Runtime#

JavaScript is fundamentally a single-threaded language: it contains a single call stack and executes one command at a time within a given thread. Despite this constraint, modern web applications handle non-blocking network requests, timers, user interactions, and file I/O smoothly.

Understanding the mechanics behind this concurrency requires examining the relationship between the Call Stack, the runtime environment (browser APIs or Node.js libuv), and the Event Loop.

The Call Stack#

The Call Stack is a Last-In, First-Out (LIFO) data structure that tracks the current execution point of the program:

  • When a function is invoked, an execution frame is pushed onto the top of the stack.
  • The frame contains the function's local variables, arguments, and return address.
  • When the function returns, its frame is popped from the stack.
  • If synchronous code blocks the stack (e.g., an intense calculation), the runtime cannot process any other operations, resulting in an unresponsive interface.

Asynchronous APIs & Background Handlers#

Asynchronous operations like fetch(), setTimeout(), and filesystem reads are not handled directly on the JavaScript call stack. Instead, they are delegated to platform APIs:

  • In browser environments, these are Web APIs provided by the browser host.
  • In Node.js, operations are scheduled through libuv thread pools and operating system kernel primitives.

When the asynchronous task completes, the platform API places the corresponding callback into one of two primary queues: the Macrotask Queue (Task Queue) or the Microtask Queue.

Microtasks vs. Macrotasks#

The distinction between task priority is one of the most critical aspects of JavaScript execution:

The Microtask Queue#

Microtasks have immediate priority over regular tasks. Common sources of microtasks include:

  • Promise.prototype.then(), catch(), and finally() callbacks
  • queueMicrotask()
  • MutationObserver callbacks (browser)
  • process.nextTick() (Node.js internal queue, processed with highest priority)

The Macrotask Queue#

Macrotasks represent independent units of work scheduled by the runtime:

  • setTimeout() and setInterval() callbacks
  • setImmediate() (Node.js)
  • UI events and network I/O callbacks

The Event Loop Execution Cycle#

The Event Loop continuously runs a deterministic evaluation cycle:

  1. Check Call Stack: If the call stack contains execution frames, let them run to completion.
  2. Drain Microtasks: Once the call stack is completely empty, the Event Loop processes the Microtask Queue. It executes every queued microtask sequentially until the queue is completely drained. If a microtask schedules another microtask, that new microtask will also execute before the loop moves forward.
  3. Render Phase (Browsers): If necessary and on interval, the browser performs style calculation, layout, and visual painting.
  4. Dequeue One Macrotask: The Event Loop takes the oldest macrotask from the Macrotask Queue and pushes its callback onto the call stack.
  5. Repeat: After that single macrotask finishes, the loop immediately checks and drains the microtask queue again before picking the next macrotask.

Practical Code Walkthrough#

Consider the following execution snippet:

javascript
console.log("1: Synchronous start");

setTimeout(() => {
  console.log("2: Macrotask timeout");
}, 0);

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

console.log("4: Synchronous end");

The resulting output is always:

text
1: Synchronous start
4: Synchronous end
3: Microtask promise
2: Macrotask timeout

Even though setTimeout has a delay of 0, the Promise callback is routed through the Microtask Queue, which executes completely before the Event Loop dequeues the first task from the Macrotask Queue.

Summary#

Mastering the Event Loop allows engineers to prevent UI freezes, understand subtle ordering bugs in asynchronous workflows, and write predictable concurrent JavaScript across client and server environments.

Further reading

Backend Development2 min read

Architecting Resilient and Predictable REST APIs

Core design patterns for building scalable, idempotent, and developer-friendly RESTful HTTP interfaces.

Backend DevelopmentRESTAPI DesignNode.js
Read article