A brief discussion on the execution order of JavaScript macrotasks and microtasks

A brief discussion on the execution order of JavaScript macrotasks and microtasks

1. JavaScript is single-threaded

JavaScript is single-threaded, which means that it can only do one thing at a time, and the next thing can only be executed after the previous thing is completed. As a result, the subsequent code cannot be executed when a time-consuming task is encountered.

Before that, we must understand synchronization and asynchrony

1. Synchronous tasks

    console.log(123);
    console.log(456);
    for (let i = 1; i <= 5; i++) {
      console.log(i);
    } 

As the name implies, it must be executed sequentially

2. Asynchronous tasks

    setTimeout(() => {
      console.log('timer');
    }, 0)
    console.log('Ultraman');

According to the normal execution order, the timer is on top, so the timer should be output first and then Ultraman.

The final result is that Ultraman is output first and then the timer. The reason is that setTimeout is an asynchronous task.

One more piece of knowledge: setTimeout's timer is asynchronous no matter how many milliseconds it is delayed. The time for each browser is also different. Each browser has its own differences, but the minimum is defined as 0 and 4 milliseconds.

2. Task queue

From the above code, we know that setTimeout is asynchronous. We can understand the execution order priority: synchronous code > asynchronous code. Therefore, the task queue is divided into two categories: 1. synchronous tasks 2. asynchronous tasks

1. Execution Stack

(1) All synchronous tasks are executed on the main thread, forming an execution context stack.

(2) In addition to the main thread, there is also a "task queue". As long as the asynchronous task has a running result, an event is placed in the "task queue".

(3) Once all synchronous tasks in the "execution stack" are executed, the system will read the "task queue" to see what events are in it. Those corresponding asynchronous tasks then end the waiting state, enter the execution stack, and start execution.

(4) The main thread continuously repeats the third step above, which is called the event loop.

Just give a pear

They both go out to eat, but P2 saves the time of going out.

After a brief understanding, let's take a deeper look at macrotasks and microtasks in asynchronous tasks.

Personal understanding: Macrotasks and microtasks can be understood as two forms of asynchronous. Asynchronous has two children: macrotasks and microtasks.

Methods in macro tasks: 1. script (can be understood as outer synchronization code, as the entry point) 2. setTimeout/setInterval

Methods in microtasks: 1. Promise 2. nextTick

The order of their execution is that microtasks are output first and then macrotasks

Saying code without proof

    setTimeout(() => {
      console.log('timer');
    }, 0)
    new Promise((resolve) => {
      console.log('synchronous code')  
      resolve('asynchronous code')
    }).then((res) => {
      console.log(res);   
    })
    console.log('Ultraman'); 

Note that new Promise creates a constructor, which is a synchronous process, while the .then method is asynchronous, so the code executes synchronously first > microtask > macrotask

In order to describe the execution process in more detail, the following diagram is a little bit complicated.

These pictures are combined

Expand your understanding of setTimeout

Question 1: Will setTimeout start counting from 0 after the synchronous code is executed?

    setTimeout(() => {
      console.log('setTimeout');
    }, 1000);
    console.log('Ultraman');
    for (let i = 0; i < 1000; i++) {
      console.log('');
    } 

At this point, I want to point out that when I am in the for loop, setTimeout will also start a timer module. Therefore, when the main thread is executed, the timer module has already started executing, so it will not wait for 1 second to execute.

(Don't assume that the synchronization is complete and then start timing.)

Question 2: Between the two timers, should the upper timer be executed first and then the lower timer?

For the test, we just need to add a timer to see who executes first.

    setTimeout(() => {
      console.log('setTimeout1');
    }, 2000);
    setTimeout(() => {
      console.log('setTimeout2');
    }, 1000); 

It turns out that if there are two timers, the one with less time will be executed in the main thread first.

Question 3: If a variable is defined as 0 and two identical timer events are set, what will the output be? (Interview question)

    i = 0
    setTimeout(() => {
      console.log(++i); //1
    }, 1000);
    setTimeout(() => {
      console.log(++i); //2 
    }, 1000);

Now you must know that timer macro tasks are not executed together but in sequence! !

Interview questions on macrotask and microtask execution order

    console.log('1');
 
    setTimeout(function () {
      console.log('2');
      process.nextTick(function () {
        console.log('3');
      })
      new Promise(function (resolve) {
        console.log('4');
        resolve();
      }).then(function () {
        console.log('5')
      })
    })
    process.nextTick(function () {
      console.log('6');
    })
    new Promise(function (resolve) {
      console.log('7');
      resolve();
    }).then(function () {
      console.log('8')
    })
 
    setTimeout(function () {
      console.log('9');
      process.nextTick(function () {
        console.log('10');
      })
      new Promise(function (resolve) {
        console.log('11');
        resolve();
      }).then(function () {
        console.log('12')
      })
    })

Answer:

The first round of execution of external synchronization code: 1 7

Second round of microtask execution: 6 8

The third round of macrotasks: First setTimeout: Synchronization 2 4 Microtask 3 5 Second setTimeout: Synchronization 9 11 Microtask 10 12

Overall answer: 1, 7, 6, 8, 2, 4, 3, 5, 9, 11, 10, 12

This concludes this article on the execution order of JavaScript macrotasks and microtasks. For more information about the execution order of JavaScript macrotasks and microtasks, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. 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 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
  • JavaScript microtasks and macrotasks explained

<<:  Summary of Linux vi command knowledge points and usage

>>:  A complete list of commonly used MySQL functions (classified and summarized)

Recommend

Vue3 draggable left and right panel split component implementation

Table of contents Breaking down components Left P...

Detailed steps to build an independent mail server on Centos7.9

Table of contents Preface 1. Configure intranet D...

MySQL Database Iron Laws (Summary)

Good database specifications help reduce the comp...

Vue custom v-has instruction, steps for button permission judgment

Table of contents Application Scenario Simply put...

Detailed explanation of the usage and differences of MySQL views and indexes

MySQL Views Simply put, a MySQL view is a shortcu...

How to install Zookeeper service on Linux system

1. Create the /usr/local/services/zookeeper folde...

9 super practical CSS tips to help designers and developers

A web designer's head must be filled with a lo...

Two ways to install the Linux subsystem in Windows 10 (with pictures and text)

Windows 10 now supports Linux subsystem, saying g...

Binary installation of mysql 5.7.23 under CentOS7

The installation information on the Internet is u...

How to install MySQL under Linux (yum and source code compilation)

Here are two ways to install MySQL under Linux: y...

MySQL establishes efficient index example analysis

This article uses examples to describe how to cre...

WeChat applet implementation anchor positioning function example

Preface In the development of small programs, we ...

SVG button example code based on CSS animation

The specific code is as follows: <a href="...

MySQL 8.0.13 installation and configuration method graphic tutorial under win10

I would like to share the installation and config...