• Web API

Browser Event loop

by Nik

added on August 17, 2023 (1y ago)

The article focuses on the event loop, the order of execution, and how developers can optimize code. The fully detailed schema:

Detailed schema of event loop

Event loop

Old operational systems didn't support multithreading and their event loop can be approximately described as a simple cycle:

while (true) {
  if (execQueue.isNotEmpty()) {
    execQueue.pop().exec();
  }
}

This code utilizes all CPU. It was so in old OS. Modern OS schedulers are utterly complicated. They have prioritization, execution queues, and many other technologies.

We can start describing the event loop as a cycle, which checks whether we have any pending tasks:

Simple cycle, which checks if we have any tasks to execute

To get a task for the execution let's draft

✍️The list of triggers that can put a task into the event loop:

  1. <script> tag

  2. Postponed tasks: setTimeout, setInterval, requestIdleCallback

  3. Event handlers from browser API: click, mousedown, input, blur, and etc.

    1. Some of the events are user-initiated like clicks, tab switching, etc.

    2. Some of them are from our code: XmlHttpRequest response handler, fetch promise resolve, and so on

  4. The promise state change. More about promises in my series

  5. Observers like DOMMutationObserver, IntersectionObserver

  6. RequestAnimationFrame

Almost everything we described above is planned through WebAPI (or browserAPI).