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

How to change the root password in MySQL 5.7

Starting from MySQL 5.7, many security updates ha...

Unicode signature BOM detailed description

Unicode Signature BOM - What is the BOM? BOM is th...

Vue implements nested routing method example

1. Nested routing is also called sub-routing. In ...

How to configure MySQL on Ubuntu 16.04 server and enable remote connection

background I am learning nodejs recently, and I r...

Raspberry Pi msmtp and mutt installation and configuration tutorial

1. Install mutt sudo apt-get install mutt 2. Inst...

Summary of commonly used commands for docker competition submission

Log in to your account export DOCKER_REGISTRY=reg...

Vue implements 3 ways to switch tabs and switch to maintain data status

3 ways to implement tab switching in Vue 1. v-sho...

CSS draw a lollipop example code

Background: Make a little progress every day, acc...

Understanding and solutions of 1px line in mobile development

Reasons why the 1px line becomes thicker When wor...

Solve the error of installing VMware Tools on Ubuntu 18.04

1. According to the online tutorial, the installa...

XHTML Getting Started Tutorial: Using the Frame Tag

<br />The frame structure allows several web...