Understanding the JavaScript Event Loop: A Simple Guide

Paul Chesa
3 min readDec 23, 2024

--

If you’ve ever wondered how JavaScript manages to multitask despite being single-threaded, you’re in the right place. Let’s break it down step by step, using simple analogies to understand concepts like the call stack, Web APIs, callback queue, and the event loop. 🎉

JavaScript is Single-Threaded

Imagine you’re at a sandwich shop, and there’s only one person making sandwiches. This person can only make one sandwich at a time. Similarly, JavaScript is single-threaded, meaning it can only execute one task at a time. This is managed by something called the call stack, which we’ll discuss next.

Call Stack: The Sandwich Maker’s To-Do List

Think of the call stack as a stack of plates at the sandwich shop. Every time a new order (function) comes in, the sandwich maker adds a plate (function) to the stack. They complete the task on the topmost plate before moving on to the next one. Once the function finishes, the plate is removed from the stack.

Example:

function greet() {
console.log('Hello!');
}

function sayGoodbye() {
console.log('Goodbye!');
}

greet();
sayGoodbye();

Here, greet() is added to the stack first. Once it's done, sayGoodbye() is added and executed. Easy peasy!

Web APIs: The Shop’s Helpers

Now, what if someone orders a sandwich that takes a while to prepare, like toasting bread? The sandwich maker doesn’t stop everything to wait; instead, they pass this task to a helper. In JavaScript, these helpers are the Web APIs provided by the browser. They handle tasks like:

  • Timers (setTimeout)
  • DOM events (e.g., onclick)
  • HTTP requests (e.g., fetch)

These tasks are handled outside of the call stack, ensuring the sandwich maker can continue working.

Example:

console.log('Start');
setTimeout(() => console.log('Toast is ready!'), 2000);
console.log('End')

Here, setTimeout hands off the toasting task to a helper, and the main thread continues.

Callback Queue: The Pickup Counter

Once the helper finishes toasting the bread, the sandwich is placed on a counter (callback queue) for the sandwich maker to pick up when they’re free. Similarly, JavaScript places completed asynchronous tasks into the callback queue, waiting for the call stack to clear.

Event Loop: The Manager

The event loop is like the shop’s manager. They keep checking if the sandwich maker’s hands (call stack) are empty. If they are, the manager takes the next task (callback) from the pickup counter (callback queue) and hands it to the sandwich maker.

Microtasks Queue: The VIP Line

Now imagine a VIP line for urgent orders. This is the microtasks queue, reserved for high-priority tasks like promises. The event loop always checks this VIP line before handling the regular pickup counter (callback queue).

Example:

console.log('Start');

Promise.resolve().then(() => console.log('VIP order!'));

setTimeout(() => console.log('Regular order!'), 0);

console.log('End');

Output:

Start
End
VIP order!
Regular order!

Here, the promise (VIP order) is handled before the setTimeout callback (regular order), even though both are ready at the same time.

Priority Handling: Ensuring Smooth Operations

To sum it all up:

  1. The event loop first checks the microtasks queue (VIP line).
  2. If it’s empty, it moves to the callback queue (regular pickup counter).

This priority handling ensures that critical tasks, like promises, are processed promptly without delaying other operations.

Wrapping Up: The Event Loop in Action

Understanding the JavaScript event loop is key to writing efficient and non-blocking code. With the call stack, Web APIs, callback queue, microtasks queue, and the event loop working together, JavaScript handles both synchronous and asynchronous tasks seamlessly.

And that, my friend, is how JavaScript — like a busy sandwich shop — manages to keep everything running smoothly despite being single-threaded. 🍔

--

--

Paul Chesa
Paul Chesa

Written by Paul Chesa

Angular developer | Frontend Developer | Proficient in Typescript and JavaScript | Parva res est

No responses yet