DEV Community

punavwalke
punavwalke

Posted on

Understanding JavaScript Event Loop (The Way It Finally Clicked for Me)

πŸ”₯ The Question That Confused Me

JavaScript is single-threaded…
So how does it handle things like:

  • API calls
  • Timers
  • User interactions

…without blocking everything?


⚠️ The Problem

JavaScript can only execute one thing at a time on a single thread.

If a long-running task blocks the thread, the entire UI freezes.

πŸ‘‰ But real-world apps don’t work like that.

So something must be managing when async code runs.


βš™οΈ What is the Event Loop?

The Event Loop is a mechanism that coordinates execution between:

  • The call stack (where code runs)
  • The task queues (where async callbacks wait)

πŸ‘‰ It doesn’t execute code itself
πŸ‘‰ It decides when code should be executed


🧩 Core Pieces You Need to Know

1. Call Stack

  • Where JavaScript executes code
  • Follows LIFO (Last In, First Out)
  • Runs synchronous code line by line

2. Web APIs

Things like:

  • setTimeout
  • fetch
  • DOM events

πŸ‘‰ These are handled by the browser, not JavaScript

Once completed, their callbacks are sent to queues.


3. Task Queue (Macrotask Queue)

Includes callbacks from:

  • setTimeout
  • setInterval
  • DOM events

4. Microtask Queue

Higher priority queue that includes:

  • Promise.then
  • queueMicrotask

⚑ Important Rule

πŸ‘‰ All microtasks are executed before macrotasks


How It All Works Together

  1. Synchronous code runs on the call stack
  2. Async operations go to Web APIs
  3. When done, callbacks move to queues
  4. The Event Loop checks:
  • If the call stack is empty
  • Then pushes tasks from queues to the stack

πŸ’₯ Let’s Test This

let id="ex1"
console.log("Start");

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

Promise.resolve().then(() => {
  console.log("Promise");
});

console.log("End");
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Pause and predict the output before reading further


βœ… Output

Start
End
Promise
Timeout


Step-by-step Breakdown

  1. Start β†’ goes to call stack β†’ executed
  2. setTimeout β†’ goes to Web API β†’ callback sent to task queue
  3. Promise.then β†’ goes to microtask queue
  4. End β†’ executed

Now stack is empty πŸ‘‡

  1. Event Loop picks microtasks first β†’ Promise
  2. Then picks macrotasks β†’ Timeout

πŸ’‘ What Finally Clicked for Me

I used to think:

setTimeout(fn, 0) runs immediately

But actually:

  • It always waits for the stack to be empty
  • And it runs after microtasks

πŸ‘‰ This explains so many β€œweird” async bugs


πŸ”š Simple Summary

  • JavaScript is single-threaded
  • The Event Loop coordinates async execution
  • Microtasks have higher priority than macrotasks

If you're learning JavaScript deeply, understanding this changes how you think about async code completely.

Top comments (0)