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! πŸŽ‰

Top comments (0)