`

kaksha.dev


Browser Event Loop

Javascript at its core is single threaded. With that said, there are lot of asynchronus operations to be handled and these are handled with browser event loop mechanism. The JavaScript Event Loop is the mechanism that allows JavaScript (single-threaded) to perform asynchronous operations without blocking the main thread.

The event loop consists of below primary components:

  1. Main Stack
  2. Web APIs (a.k.a. Browser apis)
  3. Queue
    • Callback / Tasks / Macro Tasks
    • Micro Tasks Queue

Browser APIs

Browser APIs are built-in interfaces provided by the browser that extend JavaScript with capabilities such as manipulating the DOM, making network requests, handling timers, storing data, accessing device features, and running background tasks. Some of the most commonly used Browser APIs are as follows:

Event loop in browser

The JavaScript Event Loop is the mechanism that allows single-threaded JavaScript to perform asynchronous operations without blocking the main thread.

Event Loop in Browser

XMLHttpRequest

XMLHttpRequest is a browser API traditionally used for making HTTP network requests. Now, fetch API is the preferred approach for most use cases.

Execution flow in browser with XMLHttpRequest

Event Loop with XMLHttpRequest

Web Worker

A Web Worker is a separate JavaScript thread, not a task. It has its own event loop, and within that event loop it processes macro tasks and microtasks just like the main thread does.

Execution flow in browser with Web worker

Event Loop with Web Worker