Sobes.tech
Middle+

How does the event loop work in the web API?

sobes.tech AI

Answer from AI

The event loop in JavaScript (in the context of a web browser) is a mechanism that allows asynchronous operations to be performed without blocking the main execution thread. It consists of several components:

  • Heap: Memory area where objects are stored.
  • Call Stack: A LIFO data structure that tracks the execution of synchronous functions.
  • Web APIs: Provided by the browser (DOM, AJAX, setTimeout, setInterval, Event Listeners, etc.). They are not part of the JavaScript engine.
  • Callback Queue / Task Queue: Message queue for executing asynchronous tasks.
  • Microtask Queue: A priority queue for microtasks (Promise.then(), async/await, queueMicrotask). It executes before the task queue.
  • Event Loop: Continuously checks the call stack and the queue. If the stack is empty, it moves the first handler from the microtask queue (if any) to the stack. After the microtask queue is emptied, it moves the first handler from the task queue to the stack.

The process works as follows:

  1. Synchronous code executes and functions are placed on the call stack.
  2. When an asynchronous operation is encountered (e.g., setTimeout), it is handed over to the corresponding Web API. Synchronous code execution continues.
  3. The Web API performs the operation in the background.
  4. After the asynchronous operation completes, its handler (callback) is placed in the task queue (for regular async ops) or the microtask queue (for promises).
  5. The event loop constantly checks the call stack. If the stack is empty:
    • It checks the microtask queue. If there are handlers, it moves them to the call stack for execution until the microtask queue is empty.
    • Then it checks the task queue. If there are handlers, it moves the first handler from the task queue to the call stack for execution.
  6. This process repeats, allowing asynchronous operations to be performed without blocking the main thread.

Example with setTimeout:

// This code runs on the call stack
console.log('Start');

// setTimeout - Web API. Callback is placed in the task queue after 0ms.
// Actual execution may be delayed due to the event loop.
setTimeout(() => {
  console.log('Timeout');
}, 0);

// This code runs on the call stack after setTimeout
console.log('End');

// Output:
// Start
// End
// Timeout

Example with promises:

// runs on the call stack
console.log('A');

// promise. then() callback is placed in the microtask queue
Promise.resolve().then(() => {
  console.log('B');
});

// runs on the call stack
console.log('C');

// Output:
// A
// C
// B

Execution order: synchronous code ('A', 'C'), then the microtask queue is emptied ('B'), then the task queue.