Event Loop | Dataplexa

Event Loop

JavaScript may look simple on the surface, but behind the scenes it follows a very precise execution model.

The event loop is the reason JavaScript can handle asynchronous tasks while still running on a single thread.


JavaScript Is Single-Threaded

JavaScript executes code in a single thread. This means:

  • Only one task runs at a time
  • Long tasks can block execution
  • Asynchronous handling is essential

The event loop solves this problem.


Main Components Involved

The event loop works with three main components:

  • Call Stack
  • Task Queue (Callback Queue)
  • Event Loop

Together, they control execution flow.


The Call Stack

The call stack keeps track of function calls.

When a function is called:

  • It is added to the stack
  • It runs
  • It is removed after completion

The stack must be empty before new tasks can run.


The Task Queue

Asynchronous tasks (like timers and events) do not go directly to the call stack.

Instead, their callbacks wait in the task queue until the stack is free.


setTimeout(function () {
  console.log("From queue");
}, 0);

console.log("From stack");
  

Even with a delay of zero, the callback waits for the stack to clear.


What the Event Loop Does

The event loop constantly checks:

  • Is the call stack empty?
  • If yes, is there something in the queue?

If both conditions are met, the event loop moves the next callback from the queue to the stack.


Execution Order Example

Consider this code:


console.log("Start");

setTimeout(() => {
  console.log("Async Task");
}, 0);

console.log("End");
  

Output order:

  • Start
  • End
  • Async Task

This happens because of the event loop.


Why the Event Loop Matters

Understanding the event loop helps you:

  • Debug asynchronous bugs
  • Predict execution order
  • Write non-blocking code

It is essential for performance-sensitive applications.


Real-World Analogy

Think of the call stack as a cashier.

  • Only one customer is served at a time
  • Others wait in a queue
  • The cashier calls the next person when free

That process is the event loop.


Common Beginner Confusions

  • Assuming setTimeout runs immediately
  • Thinking async code blocks execution
  • Ignoring execution order

Timing depends on the event loop, not delay values alone.


Thumb Rules

  • JavaScript runs one task at a time
  • Async callbacks wait in a queue
  • The event loop controls execution flow
  • Zero delay does not mean immediate execution

What Comes Next?

Now that you understand how JavaScript executes code, the next step is understanding how execution contexts are created and managed.

In the next lesson, we will explore execution context.