JavaScript microtasks and macrotasks explained

JavaScript microtasks and macrotasks explained

Preface:

js is a single-threaded language, so it is impossible for it to be asynchronous. However, the host environment of js (such as browser, node) is multi-threaded. The host environment makes js have asynchronous properties in some way (event-driven). In js, we generally divide all tasks into two categories, one is synchronous task and the other is asynchronous task. Among asynchronous tasks, there are more detailed classifications, namely microtasks and macrotasks.

1. Concept

1.1 Macro Tasks

Macro tasks---- setTimeout , setInterval , DOM events, AJAX requests

In order to ensure that the JS internal tasks and DOM tasks can be executed in order, the browser will re-render the page after one task is completed and before the next task is started (task->render->task->…)

1.2 Microtasks

Microtasks ---- Promise , async / await

Microtasks are usually tasks that need to be executed immediately after the current synchronous task is completed, such as providing feedback on a series of actions, or tasks that need to be executed asynchronously without allocating a new task, which can reduce performance overhead.

2. Execution Order

Let's look at a piece of code first, and then discuss the execution order:

   console.log(1)
    setTimeout(() => {
      console.log(2)
    })
    Promise.resolve().then(() => {
      console.log(3)
    })
    console.log(4)


The result printed by the above code is 1 4 3 2. From the above code, we can conclude that their execution order is:

​ Execute the synchronous code first. When encountering an asynchronous macro task, put the asynchronous macro task into the macro task queue. When encountering an asynchronous micro task, put the asynchronous micro task into the micro task list. When all the synchronous codes are executed, transfer the asynchronous micro task from the list to the main thread for execution. After the asynchronous micro task is executed, transfer the asynchronous macro task from the queue to the main thread for execution. The cycle continues until all tasks are executed.

Note: Microtasks are executed before page rendering.

3. Task Relationship

Macro tasks are the mainstream. When js starts to be executed, a macro task is started. In the macro task, instructions are executed one by one. There can be multiple macro tasks at the same time, but they will be executed one by one in sequence.

Each macrotask can be followed by a microtask queue. If there are instructions or methods in the microtask queue, they will be executed first. If not, start executing the next macro task until all macro tasks are completed.

4. Task details

Why do microtasks still exist after macrotasks? That is because macrotasks take up too much performance. When some methods that were prepared earlier are needed and are executed last, and you don’t want to add a new macrotask, you can put these methods one by one in the microtask queue. After the code in this macrotask is executed, the microtask queue will be executed.

Therefore, when the current synchronous code is executed and an asynchronous task is encountered, if it is an asynchronous macro task, it is placed in the next round of macro task queue; if it is an asynchronous micro task, it is placed in the micro task queue and follows the current macro task. A microtask is equivalent to the small tail of a macrotask. Therefore, when the current macrotask is executed, the asynchronous microtask waiting behind it will be immediately put into the queue for continued execution. The asynchronous macrotask needs to wait until the next round, which causes the asynchronous microtask to be executed before the macrotask.

This is the end of this article about JavaScript microtasks and macrotasks. For more relevant JavaScript microtasks and macrotasks, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Details on macrotasks and microtasks in JavaScript
  • A brief discussion on macrotasks and microtasks in js
  • JavaScript macrotasks and microtasks
  • A brief discussion on the execution order of JavaScript macrotasks and microtasks
  • A brief discussion on the principles of JavaScript event loop microtasks and macrotask queues
  • Analysis of JavaScript event loop and macro-task and micro-task principles
  • JS event loop mechanism event loop macro task micro task principle analysis

<<:  A brief discussion on the role of HTML empty links

>>:  CSS realizes the realization of background image screen adaptation

Recommend

Detailed steps for completely uninstalling MySQL 5.7

This article mainly summarizes various problems o...

A detailed introduction to wget command in Linux

Table of contents First install wget View Help Ma...

Docker installation and deployment example on Linux

After reading the following article, you can depl...

Mysql case analysis of transaction isolation level

Table of contents 1. Theory SERIALIZABLE REPEATAB...

Detailed explanation of JS browser event model

Table of contents What is an event A Simple Examp...

JavaScript navigator.userAgent obtains browser information case explanation

The browser is probably the most familiar tool fo...

Springboot+VUE to realize login and registration

This article example shares the specific code of ...

Analysis of the difference between HTML relative path and absolute path

HTML beginners often encounter the problem of how ...

How to use Vue cache function

Table of contents Cache function in vue2 Transfor...

CentOS 7 installation and configuration method graphic tutorial

This article records the detailed installation tu...

Detailed tutorial on installing Docker and docker-compose suite on Windows

Table of contents Introduction Download and insta...

Docker advanced method of rapid expansion

1. Command method Run the nginx service in the cr...

How to monitor oracle database using zabbix agent2

Overview In zabbix version 5.0 and above, a new f...

How to add and delete unique indexes for fields in MySQL

1. Add PRIMARY KEY (primary key index) mysql>A...

Common functions of MySQL basics

Table of contents 1. Common function classificati...