DEV Community

Shashi Bhushan Kumar
Shashi Bhushan Kumar

Posted on

JavaScript Event Loop Explained in Simple Words

JavaScript Event Loop Explained in Simple Words

JavaScript is single-threaded.

That means it can do one task at a time.

But then a question comes…

If JavaScript runs one thing at a time,

how does it handle:

  • setTimeout
  • API calls
  • Promises
  • async/await

πŸ‘‰ The answer is Event Loop.


🧠 First, Understand This

JavaScript runtime has 4 important parts:

  1. Call Stack – where code runs
  2. Web APIs – handles timers, fetch, DOM events
  3. Callback Queue – waiting area for async tasks
  4. Event Loop – the manager

🍽 Real-Life Example (Very Simple)

Imagine a restaurant with only one chef πŸ‘¨β€πŸ³

Two customers order:

  • Tea (fast)
  • Biryani (takes time)

The chef:

  • Starts cooking biryani
  • Serves tea meanwhile
  • When biryani is ready β†’ serves it

The chef does not stand waiting.

That smart system = Event Loop


βš™οΈ How Event Loop Works

Step 1: Code runs in the Call Stack

Step 2: Async tasks (like setTimeout) go to Web APIs

Step 3: After completion, they move to Callback Queue

Step 4: Event Loop keeps checking:

β€œIs the Call Stack empty?”

If YES β†’

It pushes the task from Queue β†’ into Stack β†’ executes it.


πŸ’» Example Code

console.log("Start");

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

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

Output:

Start
End
Timeout
Enter fullscreen mode Exit fullscreen mode

πŸ€” Why Does This Happen?

Even though delay is 0:

  • setTimeout goes to Web API first
  • Then to Callback Queue
  • Event Loop waits until Stack is empty
  • Then executes it

That’s why "End" prints before "Timeout".


🎯 Important Interview Point

JavaScript is:

  • Single-threaded
  • But asynchronous
  • Because of the Event Loop

If someone asks:

β€œHow does JavaScript handle async code?”

Now you can explain it clearly and confidently.

Top comments (0)