On this page

The JavaScript Event Loop

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

JavaScript is a single-threaded language, which means it has one Call Stack and can execute only one piece of code at a time. In a synchronous environment, a long-running script would "block" the thread, causing the browser to become unresponsive. The Event Loop is the specialized mechanism that allows JavaScript to perform non-blocking, asynchronous operations by offloading tasks to the browser environment and coordinating their execution.

The Architectural Components​

To understand how concurrency works, you must visualize the four primary components of the JavaScript runtime environment: the Call Stack, Web APIs, the Task Queue, and the Event Loop itself.

The Call Stack​

The Call Stack follows a LIFO (Last In, First Out) structure. When a function is invoked, it is "pushed" onto the stack. When the function returns a value or finishes executing, it is "popped" off the stack. If the stack is busy, JavaScript cannot do anything else.

Web APIs (Browser Environment)​

While the JavaScript engine (like V8) is single-threaded, the browser is not. Browsers provide Web APIs (such as setTimeout, DOM events, and fetch) that run in the background. When you call an asynchronous function, JavaScript hands the task over to these APIs and moves on to the next line of code in the stack.

The Task Queue (Callback Queue)​

Once a Web API finishes its task (e.g., a timer expires), it does not push the result back to the Call Stack immediately. Instead, it sends the callback function to the Task Queue. This is a "waiting room" for code that is ready to be executed.

The Event Loop​

The Event Loop is a constant process that monitors both the Call Stack and the Task Queue. Its job is simple but vital: If the Call Stack is empty, the Event Loop takes the first task from the Task Queue and pushes it onto the stack for execution.

The Execution Workflow​

The coordination between these components follows a strict sequence. Consider the following example:


console.log("Start");



setTimeout(() => {

  console.log("Async Task");

}, 0);



console.log("End");

Despite the timer being set to 0 milliseconds, the output will be:

  1. Start
  2. End
  3. Async Task

Step-by-Step Analysis​

  1. console.log("Start") is pushed onto the stack, executed, and popped off.
  2. setTimeout is pushed onto the stack. The JavaScript engine recognizes this as a Web API task and hands the timer to the browser. setTimeout is then popped off the stack.
  3. The browser waits 0ms. Once finished, it moves the anonymous function () => { console.log("Async Task") } into the Task Queue.
  4. While the browser was handling the timer, the engine immediately moved to console.log("End") , pushed it to the stack, executed it, and popped it.
  5. Now the Call Stack is empty. The Event Loop notices this and checks the Task Queue.
  6. The Event Loop moves the Async Task function from the queue to the Call Stack, where it is finally executed.

Macro-tasks vs. Micro-tasks​

In modern JavaScript, the Task Queue is subdivided to prioritize certain types of operations. Understanding this distinction is essential for predicting the order of execution in complex applications.

Macro-tasks​

These include standard asynchronous operations like setTimeout, setInterval, and I/O tasks. The Event Loop processes one macro-task per loop iteration.

Micro-tasks​

These primarily include Promises (the .then/catch/finally handlers) and queueMicrotask. Micro-tasks have a higher priority than macro-tasks. The Event Loop will execute all pending micro-tasks in the micro-task queue before moving on to the next macro-task.

Blocking the Event Loop​

Because the Event Loop can only push tasks when the stack is empty, performing heavy calculations (like processing a massive loop) will "starve" the Event Loop. If the stack never clears, the Event Loop can never pull tasks from the queue, resulting in a "frozen" user interface.

Professional Implementation Rule​

Never perform CPU-intensive synchronous work on the main thread. If a task is heavy, break it into smaller asynchronous chunks or utilize Web Workers to keep the Call Stack clear and the Event Loop flowing.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Asynchronous JavaScript

Next

Callbacks