[JS] Macro tasks and micro tasks

In JavaScript, tasks are divided into:

  • macro task macro task
  • micro task micro task

There are certain differences in their execution order , and understanding their execution mechanism is very important for handling asynchronous operations.

macro task

Macro tasks are task sources provided by the JavaScript engine, which usually include the following situations:

  • main code block
  • setTimeout and SetInterval callback functions
  • I/O operations (such as file reading and writing, network requests, etc.)
  • UI rendering

Each macro task will be executed at different stages of the event loop, and there will be an execution order between macro tasks, that is, first in, first out.

microtasks

Microtasks are task sources provided by Promise, MutationObserve, process.nextTick, etc.

Common microtasks include:

  • Promise callback function
    • .then()、.catch()、finally()
  • MutationObserver callback function
    • It is a js API used to monitor DOM changes
  • process.nextTick
    • process.nextTick is a special function in Node.js that is used to execute a callback function immediately after the current execution stack is completed. It provides a method to insert callback functions into the event loop's microtask queue, and has a higher priority than Promise's microtasks.

The microtask will be executed immediately after the current macrotask is completed without waiting for the next macrotask. In the same macrotask, all microtasks will be executed in the order in which they were created.

The basic flow of the event loop is as follows:

  1. Execute the synchronous code of the current macro task.
  2. Check whether there is a microtask queue, and if it exists, execute all microtasks in sequence.
  3. Performs the browser's rendering operations (if any).
  4. Execute the next macro task.

Sample code

console.log('1');

setTimeout(function() {
    
    
  console.log('2');
}, 0);

Promise.resolve().then(function() {
    
    
  console.log('3');
});

console.log('4');

在上述代码中,按照执行顺序,输出结果为:
1
4
3
2

The explanation is as follows:

1. 首先,同步代码 console.log('1') 和 console.log('4') 都会立即执行,分别打印数字 1和4。
2. 然后,遇到 setTimeout,它是一个宏任务,会被放到宏任务队列中,等待执行。
3. 接着,遇到 Promise.resolve().then(),它是一个微任务,会被放到微任务队列中,等待执行。
4. 所有同步代码执行完毕后,执行微任务队列中的微任务,打印数字 3。
5. 最后,执行宏任务队列中的宏任务,即 setTimeout 的回调函数,打印数字 2。

Summary: Microtasks have a higher priority than macrotasks , and microtasks will be executed immediately after the current macrotask is completed.

Guess you like

Origin blog.csdn.net/qq_53931766/article/details/132224190