The JS Event Loop
By Christopher Robison
The Call Stack: Where It All Begins
Heap: Object Storage
The Heap is where objects are stored. Unlike the stack, which follows a last-in, first-out model, the Heap is unstructured, making it ideal for data storage.
The Event Queue: A Waiting Room
The Event Loop: The Grand Orchestrator
A Simple Analogy
Imagine you’re cooking in a kitchen. You’ve got pasta boiling on one burner and sauce simmering on another. You can’t leave the pasta unattended, but you also need to stir the sauce. The Event Loop is like you—the chef—constantly checking each pot and knowing when to switch tasks to make sure nothing burns.
A Real-World Example
Let’s say you’ve got a button on your webpage that, when clicked, fetches data from an API. When the button is clicked, a ‘click’ event is registered, and its callback function is sent to the Event Queue. The Event Loop waits for the Call Stack to empty before moving the ‘click’ event’s callback function for execution. Once executed, the API data appears on your webpage—smooth and efficient.