Event Loop

22/11/2024
In JavaScript, everything operates on a single thread, which makes handling asynchronous tasks like function calls and API requests a significant challenge. The event loop is a crucial mechanism that coordinates all activities and ensures that your JavaScript application remains smooth and uninterrupted.

JavaScript is a single-threaded language

JavaScript is a single-threaded language, meaning it executes one task at a time.

This presents a major limitation when handling asynchronous tasks such as:

  • API calls
  • DOM manipulation
  • Event handling
  • Timers

What is the Event Loop?

The event loop is a mechanism that manages the execution of asynchronous tasks (such as callbacks, promises, and async/await), ensuring they are processed in the correct order.

Event Loop Diagram

Main components

  • Call Stack
    JavaScript uses the call stack to keep track of the functions currently being executed.
    It operates on a FILO (First In, Last Out) principle.

  • Callback Queue (Task Queue)
    Asynchronous operations such as I/O tasks or timers are handled by the browser or Node.js runtime.
    Once completed, their callbacks are placed into the callback (task) queue.

  • Microtask Queue
    A queue with higher priority than the task queue. It is used for:

    • Promise callbacks (thencatchfinally)
    • Continuation of async functions after the await keyword
    • MutationObserver callbacks
    • Callbacks scheduled via queueMicrotask

The process of the Event Loop

The event loop continuously checks whether the call stack is empty.

If the call stack is empty:

  1. It first processes all tasks in the Microtask Queue
  2. Then it takes a task from the Task (Callback) Queue
  3. Pushes it onto the call stack for execution

This ensures that asynchronous tasks are executed in the correct order without blocking the main execution thread.

Execution order

  • "Start" is printed
  • "End" is printed immediately
  • After 2 seconds, "Inside setTimeout" is printed

The Event Loop ensures that JavaScript continues executing subsequent code without being blocked by the setTimeout delay.


Conclusion

Understanding the Event LoopTask Queue, and Microtask Queue is essential for writing efficient asynchronous JavaScript.

The Event Loop coordinates task execution by:

  • Always prioritizing the Microtask Queue
  • Ensuring promises and async operations are resolved before moving on to tasks in the Task Queue

This design helps JavaScript remain non-blocking while handling complex asynchronous workflows.


References

Dropdown icon

Blog liên quan

Dropdown icon
Contact Us