The browser

// The new Version of Node looks exactly the same as the browser did 10 years ago
setTimeout((a)= >{
    console.log('time1');
    Promise.resolve().then(data= >{
        console.log('p1')})},0)
Promise.resolve().then(data= >{
    console.log('p2');
    setTimeout((a)= >{
        console.log('time2'); })}); Results: P2, time1, p1, time2// When the macro task is finished, the microtask will be cleared first. After the microtask is finished, the macro task will be executed (only one is taken out to execute). After the execution, the microtask will be cleared again
// Macro task: UI thread script setTimeout setImmediate MessageChannel
// Microtasks: THEN (internal THEN execution order takes precedence over setTimeout) MutationObserver
Copy the code

The node event loop

We’re only going to focus on three of the five stages

  • Timer – various setTimout setInterval
  • Poll – The callback for reading and writing of various FS files
  • Check – “setImmediate

Tips: Microtask Promise Process. NextTick (Execute before Promise)

Execution process:

Just like in the browser, the main stack of code is finished, all the microtasks are emptied, then the timer phase, a macro task is taken out, all the microtasks are emptied, and so on. If the fs callback is not empty, the system enters the poll phase. If the FS callback is not empty, the system stops in the poll phase and waits for the callback in other phases to be executed.

// eg1: These two lines are not necessarily first, because setTimeout is generally 1-4ms, if the machine performance is very good, within 4ms,
// After executing the main stack code, it will skip the timer phase because the timer is out of time
// go to poll, go to check
setTimeout((a)= >{
    console.log('timeout');
},0)
setImmediate((a)= >{
    console.log('setImmidate');
})


// eg2: setImmidate, timeout
// If the fs callback is performed in the poll stage, the callback queue in the check stage will not be empty
let fs = require('fs');
fs.readFile('./template.html',()=>{
    setTimeout((a)= >{
        console.log('timeout');
    },5)
    setImmediate((a)= >{
        console.log('setImmidate'); })})Copy the code