[JavaScript] macro task and micro task

Before we talked about JavaScript’s asynchronous mechanism and event loop [JavaScript] event execution mechanism, synchronization and asynchronous, event loop (event loop) , we talked about JavaScript is divided into synchronous tasks and asynchronous tasks , but in fact JavaScript has made asynchronous tasks Further division, subdivided into macro tasks and micro tasks .

1. Introduction to macro tasks and micro tasks

Macrotasks generally include:

  • Asynchronous Ajax requests
  • Timer (setTimeout, setInterval)
  • file operation
  • Other macro tasks
    insert image description here
    [Note] The whole script is also regarded as a macro task.

Microtasks generally include:

  • Promise.then、.catch 和 .finally
  • process.nextTick
  • other microtasks
    insert image description here

2. The execution mechanism of macro tasks and micro tasks

After each macrotask is executed, it will check whether there are microtasks to be executed. If so, after executing all microtasks , continue to execute the next macrotask. That is to say, every time a macro task is executed, the micro task queue must be checked and cleared before continuing to execute the next macro task.

Let's analyze the task execution process:

  • From the macro task queue, find the first executed macro task (that is, the entire script script ) according to the order of entering the queue, put it into the call stack, and start execution;
  • According to the code sequence, all synchronization tasks under the macro task are executed in sequence . If other macro tasks or micro tasks are encountered during the period, they are pushed into the corresponding task queue.
  • After executing all the synchronous tasks under the macrotask, that is, after the call stack is cleared , the macrotask is pushed out of the macrotask queue, and then the microtask queue starts to execute the microtasks in order according to the queue entry order until the microtask queue is emptied ;
  • When the microtask queue is emptied, an event loop ends ;
  • Then, from the macro task queue, find the next macro task to be executed , repeat 1-4 , and start the second event loop until the macro task queue is emptied.

【Notice】

3. Examples

Look at a piece of code and analyze its output:

console.log("a");

setTimeout(function () {
    
    
    console.log("b");
    new Promise((resolve) => {
    
    
            console.log("c");
            resolve();
        })
        .then(function () {
    
    
            console.log("d");
        })
}, 0);

new Promise((resolve) => {
    
    
        console.log("e");
        resolve();
    })
    .then(function () {
    
    
        console.log("f");
    })
    .then(function () {
    
    
        console.log("g");
    });

console.log("h");

Perform process analysis:

  • First, the entire code is pushed into the macro task queue, and the synchronization task is executed from the first line , and the first line is printed on the console 'a'; (here reflects the first point of attention )
  • Then see the setTimeout function , the whole is pushed into the macro task queue;
  • The code goes directly to the new Promise line, the new Promise function is executed immediately, so it is printed on the console 'e', resolve() is executed, and then the first .then is pushed into the microtask queue;
  • Then continue to execute the next synchronization task, the code comes to the last line and prints on the console 'h'.

At this point, the first macrotask is executed, and then it is removed from the macrotask queue, and the microtask queue starts to be emptied.

  • At this time, there is the first .then in the microtask queue , so enter the first .then and print it on the console 'f';
  • When the first .then is executed, it is found that there is another .then behind. At this time, the second .then is pushed into the microtask queue, and the first .then is executed and removed from the microtask queue;
  • At this time, the microtask queue is still not cleared, and there is a second .then queued, so similar to the above, it is printed on the console 'g'.
  • The second .then is executed and removed from the microtask queue. (This reflects the second point of attention )

At this point the microtask queue is cleared. The first event loop is completed. Then enter the second macro task, which is the setTimeout function.

  • Basically similar to the above steps, it also starts with the synchronization task and prints it on the console 'b';
  • Then come to the new Promise line, print it on the console 'c', execute resolve(), and then .then is pushed into the microtask queue;
  • The current macro task is completed, it is removed from the macro task queue, and the micro task queue starts to be emptied, enters the .then function, and prints on the console 'd';
  • The current microtask is completed and removed from the microtask queue;
  • The microtask queue has been emptied and there are no new microtasks.

At this point all the code has finished running. The output of the operation is: aehfgbcd.

Four. Summary

This article introduces macrotasks and microtasks and their operating mechanism in detail, and demonstrates how to execute macrotasks and microtasks through an example. About async and await, the operating mechanism of macrotasks and microtasks involved in page rendering, You can refer to make some animations and learn about EventLoop (from Dewey, a rare earth nugget).

Guess you like

Origin blog.csdn.net/weixin_43790653/article/details/123781431