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

IIS 7.5 uses URL Rewrite module to achieve web page redirection

We all know that Apache can easily set rewrites f...

MySQL FAQ series: How to avoid a sudden increase in the size of the ibdata1 file

0. Introduction What is the ibdata1 file? ibdata1...

When backing up files in Centos7, add the backup date to the backup file

Linux uses files as the basis to manage the devic...

MySQL incremental backup and breakpoint recovery script example

Introduction Incremental backup means that after ...

Using react-beautiful-dnd to implement drag and drop between lists

Table of contents Why choose react-beautiful-dnd ...

Should I use Bootstrap or jQuery Mobile for mobile web wap

Solving the problem Bootstrap is a CSS framework ...

Detailed steps for porting busybox to build a minimal root file system

Busybox: A Swiss Army knife filled with small com...

Simple tips to increase web page loading speed

The loading speed of a web page is an important in...

Teach you how to implement Vue3 Reactivity

Table of contents Preface start A little thought ...

About vue component switching, dynamic components, component caching

Table of contents 1. Component switching method M...

Do you know how many connections a Linux server can handle?

Preface First, let's see how to identify a TC...

...

Summary of Vue3 combined with TypeScript project development practice

Table of contents Overview 1. Compositon API 1. W...