#atom
Content:
The event loop is a fundamental concept in JavaScript that enables asynchronous programming. It is the mechanism that allows JavaScript to perform non-blocking I/O operations, despite being single-threaded. The event loop continuously checks the call stack and the task queue, ensuring that asynchronous tasks (like callbacks, Promises, and timers) are executed in the correct order.

Key Concepts:

  1. Single-Threaded Nature of JavaScript:

    • JavaScript runs on a single thread, meaning it can only execute one task at a time.
    • However, it can handle asynchronous operations efficiently using the event loop.
  2. Call Stack:

    • The call stack is a data structure that tracks the execution of function calls.
    • When a function is called, it is added to the top of the stack. When the function returns, it is removed from the stack.
    • Example:
      function foo() {
        console.log("foo");
      }
      function bar() {
        foo();
        console.log("bar");
      }
      bar(); // Output: "foo", "bar"
      
  3. Web APIs:

    • Browser-provided APIs (e.g., setTimeout, fetch, DOM events) handle tasks outside the main thread.
    • When an asynchronous operation (like a timer or network request) is initiated, it is offloaded to the Web API, freeing up the call stack.
  4. Callback Queue (Task Queue):

    • Once an asynchronous operation completes, its callback is placed in the callback queue.
    • The event loop monitors the call stack and the callback queue. When the call stack is empty, it moves callbacks from the queue to the stack for execution.
  5. Microtask Queue:

    • Microtasks are tasks with higher priority than regular callbacks.
    • Promises and MutationObserver callbacks are placed in the microtask queue.
    • The event loop processes all microtasks before moving to the callback queue.
  6. Event Loop Workflow:

    • The event loop continuously checks:
      1. If the call stack is empty.
      2. If there are any microtasks (e.g., Promise callbacks).
      3. If there are any tasks in the callback queue (e.g., setTimeout callbacks).
    • Example:
      console.log("Start");
      
      setTimeout(() => {
        console.log("Timeout callback");
      }, 0);
      
      Promise.resolve().then(() => {
        console.log("Promise resolved");
      });
      
      console.log("End");
      
      // Output:
      // "Start"
      // "End"
      // "Promise resolved"
      // "Timeout callback"
      

Example: Event Loop in Action

console.log("Script start");

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

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

console.log("Script end");

// Output:
// "Script start"
// "Script end"
// "Promise 1"
// "Promise 2"
// "setTimeout"

Key Points:

Visual Representation of the Event Loop:

  1. Call Stack: Executes synchronous code.
  2. Web APIs: Handle asynchronous operations.
  3. Callback Queue: Holds callbacks from completed asynchronous operations.
  4. Microtask Queue: Holds higher-priority callbacks (e.g., Promises).
  5. Event Loop: Moves tasks from the queues to the call stack when it is empty.

Linked Cards:

Tags: #JavaScript #EventLoop #AsynchronousProgramming #CallStack #Microtasks #WebAPIs

Connections:


Sources: