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

Docker installation and configuration command code examples

Docker installation Install dependency packages s...

Understand the basics of Navicat for MySQL in one article

Table of contents 1. Database Operation 2. Data T...

How to use xshell to connect to Linux in VMware (2 methods)

【Foreword】 Recently I want to stress test ITOO...

Example of how to configure nginx in centos server

Download the secure terminal MobaXterm_Personal F...

Detailed explanation of React event binding

1. What is In react applications, event names are...

Explanation of the new feature of Hadoop 2.X, the recycle bin function

By turning on the Recycle Bin function, you can r...

Introduction to the use of select optgroup tag in html

Occasionally, I need to group select contents. In ...

Example of how to change the line spacing of HTML table

When using HTML tables, we sometimes need to chan...

Implementation of HTML sliding floating ball menu effect

CSS Styles html,body{ width: 100%; height: 100%; ...

Detailed explanation of Vue's live broadcast function

Recently, the company happened to be doing live b...