DEV Community

Cover image for Understanding the JavaScript Event Loop (Made Simple)
Amarjit yadav
Amarjit yadav

Posted on

Understanding the JavaScript Event Loop (Made Simple)

Understanding the JavaScript Event Loop (Made Simple)

The JavaScript event loop is what makes asynchronous programming in JavaScript possible. Here's a simple explanation!


🧠 Key Concepts

1. Single-Threaded

JavaScript can only do one thing at a time because it’s single-threaded.

console.log("Task 1");
console.log("Task 2");
Enter fullscreen mode Exit fullscreen mode

👉 Output:

Task 1
Task 2
Enter fullscreen mode Exit fullscreen mode

2. Synchronous vs. Asynchronous

  • Synchronous tasks: Run in order, one after another.
  • Asynchronous tasks: Don't block the main thread; they wait until they're ready to run.
console.log("Start");

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

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

👉 Output:

Start
End
Async Task
Enter fullscreen mode Exit fullscreen mode

🔄 How the Event Loop Works

  1. Call Stack

    • The place where tasks are executed one by one.
    • When a function runs, it gets added to the stack. When it finishes, it gets removed.
  2. Web APIs

    • Asynchronous tasks (like setTimeout) are handled here. They wait in the background.
  3. Callback Queue

    • Once the asynchronous task finishes, its callback is added to the queue.
  4. Event Loop

    • The event loop checks:
      1. Is the call stack empty?
      2. If YES, it takes tasks from the callback queue and pushes them to the stack.

✨ Example: Step-by-Step

console.log("Start");

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

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

1️⃣ Call Stack

Step Call Stack Notes
1 console.log Logs "Start"
2 setTimeout Registers timeout task
3 console.log Logs "End"

2️⃣ Web APIs

  • setTimeout moves to Web APIs and starts the timer.

3️⃣ Callback Queue

  • After 2000ms, the callback (() => console.log("Timeout Task")) moves to the queue.

4️⃣ Event Loop

  • The event loop checks if the call stack is empty.
  • The callback is moved to the stack and executed.

👉 Final Output:

Start
End
Timeout Task
Enter fullscreen mode Exit fullscreen mode

🚀 Visualizing the Event Loop

To truly understand the event loop, check out these resources:

Happy coding! 🎉

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay