How the Event Loop Works in JavaScript Explained

Pawan SPawan S
1 min read

JavaScript is single-threaded, it executes one command at a time in a specific order. However, it can handle asynchronous operations thanks to the event loop.

The event loop is a mechanism that manages the execution of multiple pieces of code, handling tasks like I/O operations, network requests, timers, and user interactions.

How the Event Loop Works

  1. Call Stack:

    • The call stack is where JavaScript keeps track of the function calls. When a function is called, it's added to the stack. When the function returns, it’s removed from the stack.
  2. Web APIs:

    • Web APIs (provided by the browser) handle asynchronous operations like setTimeout, fetch, and DOM events. When an asynchronous operation is initiated, the function is passed off to a Web API, freeing up the call stack.
  3. Callback Queue:

    • Once an asynchronous operation completes, its callback function is placed in the callback queue (or task queue).
  4. Event Loop:

    • The event loop continuously checks the call stack and the callback queue. If the call stack is empty, the event loop pushes the first callback from the queue to the call stack to be executed.
console.log("Start");

setTimeout(() => {
    console.log("Timeout finished");
}, 2000);

console.log("End");
0
Subscribe to my newsletter

Read articles from Pawan S directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Pawan S
Pawan S

Understanding technology.