JavaScript Eventloop Explained in Detail

Posted on 2022-03-11  1 View

The eventloop mechanism is key to Javascript's implementation of pseudo-"multithreading." This part is also a question that is often asked in interviews, take a note for reference.

The execution model of JavaScript

To be clear, JavaScript is a single-threaded language. All tasks in JavaScript are divided into one of three categories:

  • Synchronization tasks
  • Asynchronous macro tasks
  • Asynchronous microtasks

JavaScript implements asynchronous tasks by frequently switching between these tasks.

JavaScript's task execution mechanism

In terms of the overall execution mechanism, JavaScript handles the task at hand in the following order:

  • If it is a synchronous task, it is executed directly in the main thread.
  • If it is an asynchronous task, register the function in the Event Table, and when the asynchronous event completes (I/O, timeout, etc.), move the one-step callback function into the Event Queue.
  • When the main thread task finishes executing, start executing the asynchronous callback task in the Event Queue (the same EventLoop is always the first microtask and then the macro task) until the execution is completed.
  • This cycle is called Event Loop.

Macro tasks? Microtasks?

How to distinguish

  • Macro tasks
    • setTimeout, setInterval, setImmediate
  • Microtasks
    • Native Promise
    • process.nextTick(node.js)
    • Object.observe
    • MutationObserver

Enforcement mechanisms

Asynchronous events in an Event Queue are executed according to the following flowchart:

Asynchronous task execution process