JS microtasks and macrotasks (commonly used in interview questions)

 

Concept:
1. Macro task: The code executed in the current call stack becomes a macro task. (main code fast, timers, etc.).
2. Micro-task: The task that needs to be executed before the next macro-task starts after the execution of the current (in this event loop) macro-task can be understood as a callback event. (promise. then, promise. nextTick, etc.). 3. The events in the macro task are placed in the callback queue and maintained by the event trigger thread; the events of the micro task are placed in the micro task queue and maintained by the js engine thread.
js execution sequence, (execute the macro task queue first and then the micro task queue)
Example 1:

for(var i=0;i<10;i++){
setTimeout(function(){
    console.log(i)
},0)
}


Output 10 of 10
'--------------------------------------------- ----------------------------------'
2, add immediate execution function

Analysis: Although the loop execution ends, the value of i has become 3. However, due to encountering a self-executing function, the value of i at that time has been locked by lockedIndex. It can also be understood that the self-executing function is part of the for loop. Every time i is traversed, the self-executing function will be executed immediately. So even though there is a delayer, the value of i at the time of immediate execution will still be retained.

for(var i=0;i<10;i++){
    (function(i){
   setTimeout(function(){
       console.log(i)
   },0)
})(i)
}



output normal i value serial number

Operating mechanism:
1. Execute a macro task in the execution stack.
2. When a microtask is encountered during execution, the microtask is added to the microtask queue.
3. After the current macro task is executed, the tasks in the micro task queue are executed immediately.
4. After the tasks in the current microtask queue are executed, the rendering is checked, and the GUI thread takes over the rendering.
5. After rendering, the js thread takes over, starts the next event loop, and executes the next macro task (taken from the event queue).
Microtasks: process.nextTick, MutationObserver, Promise.then catch finally
Macrotasks: I/O, setTimeout, setInterval, setImmediate, requestAnimationFrame
 

Guess you like

Origin blog.csdn.net/m0_46461853/article/details/126896996