Event Loops in JS Simplified

Apurv ChoudharyApurv Choudhary
2 min read

What is the Event Loop in JavaScript?

JavaScript runs in the browser and can do things like update the web page (DOM), respond to clicks, or wait for a timer. But JavaScript is single-threaded, which means it can only do one thing at a time. So how does it handle things like user clicks, timers, or fetching data from the internet without freezing the page?

That’s where the Event Loop comes in. It's like a manager that keeps track of tasks and decides when each task should run.


How JavaScript Works Behind the Scenes:

  1. Call Stack:
    Think of this as a "to-do list" where JavaScript puts tasks it’s currently running. It runs them top to bottom, one by one.

  2. Web APIs (Provided by the Browser):
    When you use things like setTimeout, fetch, or addEventListener, JavaScript sends those tasks to the browser. The browser handles them in the background—not in the main to-do list.

  3. Callback Queue:
    Once the browser is done with a task (like waiting 2 seconds for setTimeout or when someone clicks a button), it sends the task’s callback (a function) to this queue.

  4. The Event Loop (The Manager):
    This is the brain! It constantly checks:

    • “Is the call stack empty?”

    • If yes, it takes the first task from the callback queue and pushes it into the call stack so it can run.


Example in the DOM:

javascriptCopyEditdocument.getElementById("btn").addEventListener("click", function () {
  console.log("Button clicked!");
});
  • You tell JavaScript: “Hey, when the button is clicked, run this function.”

  • The browser listens for the click using a Web API.

  • When you click, the browser says: “Okay! The click happened!” and puts the function into the callback queue.

  • The event loop checks: “Is JavaScript done with its current work?” If yes, it lets the click function run on the call stack.

  • You see "Button clicked!" in the console.


Real-Life Example

Think of a chef in a kitchen (JavaScript). They cook one dish at a time (single-threaded). When a customer orders food (event like a button click), a waiter (the browser) takes the order and places it in a queue. Once the chef finishes the current dish, the manager (event loop) says, "Okay, here’s the next order" and gives it to the chef.


Why It’s Awesome

  • It keeps the page from freezing or crashing.

  • It allows your app to stay responsive even while doing background tasks.

  • It handles user interactions smoothly.

0
Subscribe to my newsletter

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

Written by

Apurv Choudhary
Apurv Choudhary