Detailed explanation of js's event loop event queue in the browser

Detailed explanation of js's event loop event queue in the browser

Preface

The following content is the event queue execution of js in the browser, which is different from that in nodejs, please note.

It is said that js is single-threaded, but it is not actually single-threaded. However, when it is executed in the browser, only one thread is allocated for execution.

Therefore, js execution is single-threaded and can only perform one task at a time, that is, one task is done at a time, and the next one is done after one is completed.

Understanding a stack and two queues

A call stack Stack.

A macro queue, macrotask, also called tasks.

A microqueue, microtask, also called jobs.

Execution process

js executes the global Script synchronization code. If any asynchronous tasks are encountered during this process, they will be added to the corresponding queue first.

When this is done, the call stack is empty.

Then the first task in the queue (micro queue first, then macro queue) is moved to the call stack to be done, one by one until all the tasks in the queue are completed.

In summary, do the synchronization tasks first, then the micro-queue tasks, and then the macro-queue tasks.

How to allocate asynchronous tasks

These asynchronous tasks include but are not limited to:

The following are assigned to the macro queue:

setTimeout
setInterval
requestAnimationFrame
I/O
UI rendering

The following are assigned to microqueues:

Promises
Object.observe
MutationObserver

Common macro queues: setTimeout, common micro queues: Promise.

Simple Example

    console.log("Synchronous Task 1");

    setTimeout(() => {
      console.log("macro task");
    });

    new Promise((resolve, reject) => {
      console.log("Synchronous Task 2");
      resolve("microtask");
    }).then((data) => {
      console.log(data);
    });

    console.log("Synchronous Task 3");

The result is (add tasks by number and execute by arrow):

It should be noted that the first layer of Promise is synchronous before the callback is executed, which is the synchronous task 2 above.

A harder example

    console.log("Synchronous Task 1");

    console.log("Synchronous Task 2");

    new Promise((resolve, reject) => {
      console.log("Synchronous Task 3");
      setTimeout(() => {
        console.log("Macro Task 1");
        Promise.resolve()
          .then(() => {
            console.log("microtask 5");
          })
          .then(() => {
            console.log("microtask 6");
          });
      });
      resolve("microtask 1");
    })
      .then((data) => {
        console.log(data);
        return "microtask 3";
      })
      .then((data) => {
        console.log(data);
      });

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

    new Promise((resolve, reject) => {
      resolve("microtask 2");
    })
      .then((data, resolve) => {
        console.log(data);
        return "microtask 4";
      })
      .then((data) => {
        console.log(data);
      });

    console.log("Synchronous Task 4");

How to view it? First look at the first layer. Red represents synchronization, green represents microtasks, and blue represents macrotasks.

We will complete the synchronization task, and then see that there are two microtasks and two macrotasks.

The original execution order might be like this (I am expressing the order here according to the serial number, please distinguish it from the simple example):

But it was not so smooth, and things were different when it came to number 6.

Because new microtasks may be generated during the execution of microtasks.

After the execution of microtask 1 above, microtask 3 will be added after microtask 2. That is, after microtask 2 is executed, it will not be the turn of the macrotask. The new microtask will continue to be executed until the microtask queue is temporarily empty.

So the four microtasks will be executed in the order they were added to the queue. At this time, if no new microtasks are generated, the macrotask will be executed:

However, it should be noted that the situation is different when the above is executed to number 5 After the macro task is executed, a new micro task is generated. Therefore, the two macro tasks are not executed smoothly and continuously, but are blocked by the inserted micro task.

(Remember that when both microtask and macrotask queues exist, microtasks must be executed first before macrotasks, even if they are generated by macrotask execution.)

So if you don’t understand the final answer, you can review the above carefully:

Summarize

This is the end of this article about the js event loop event queue in the browser. For more relevant js event loop event queue content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of the event loop (Event Loop) of JavaScript operation mechanism
  • Detailed explanation of the event loop mechanism in front-end js
  • Introduction to EventLoop in JavaScript
  • JS event loop mechanism event loop macro task micro task principle analysis
  • Analysis of JavaScript Event Loop Related Principles

<<:  IE8 uses multi-compatibility mode to display web pages normally

>>:  mysql row column conversion sample code

Recommend

MySQL 8.0.12 installation configuration method and password change

This article records the installation and configu...

Detailed Explanation of JavaScript Framework Design Patterns

Table of contents mvc mvp mvvm The source of Vue ...

How to create your first React page

Table of contents What is Rract? background React...

Differences between Windows Server 2008R2, 2012, 2016, and 2019

Table of contents Common version introduction Com...

Docker View Process, Memory, and Cup Consumption

Docker view process, memory, cup consumption Star...

CentOS6 upgrade glibc operation steps

Table of contents background Compile glibc 2.14 M...

Detailed explanation of Mysql transaction isolation level read commit

View MySQL transaction isolation level mysql> ...

Python Flask WeChat applet login process and login api implementation code

1. Let’s take a look at the effect first Data ret...

How to locate MySQL slow queries

Preface I believe that everyone has had experienc...

CSS animation property usage and example code (transition/transform/animation)

During development, a good user interface will al...

How to install Mysql5.7 in Centos6

environment Centos 6.6 MySQL 5.7 Install If the s...

jQuery achieves breathing carousel effect

This article shares the specific code of jQuery t...