Js nature of single-threaded ------- Event Loop

How to determine a browser or node environment?

node in the window is undefined; setImmediate is defined, is not defined in the browser

timer stage: This stage will perform setTimeout and setInterval

check stages: execution setImmediate

macro task [task] macro task: script (code pages), setTimeout, setInterval, I / O events, UI interaction event (click event)

micro  task [job]  微任务: Promise、process.nextTick、Promise().then()

Macro task can have multiple queues

Only a micro-task queue

SetTimeout between tasks, the smaller the number of milliseconds of delays in the implementation, inside the front row of the queue

In node inside, timers (setTimeout, setInterval) will give priority to setImmediate

setTimeout(() => {
   console.log('setTimeout')
}, 0); // time of greater than 1000, will first perform setImmediate 
setImmediate(()=> { console.log('setImmediate')})

  

console.log('start');
setTimeout(function (){
    console.log('timeout');
},10);
new Promise((resolve) => {
    console.log('promise');
    resolve()
    setTimeout(() => {
        console.log ( 'Promsie in setTimeout');
    },0);
}).then(() => {
    console.log('then');
});
console.log('end');

  

Operating mechanism

1. Perform a macro task execution stack. 

2. encountered in implementation of micro tasks, to add to the micro-micro-task job queue.

3. The current macro task is finished, the micro-mission tasks in the queue immediately. 

4. The current task execution queue micro task is completed, check the rendering, GUI thread to take over the rendering. 

5. When rendering is complete, js thread to take over, once the next event loop open, once the macro task (event queue to take) under execution.

Guess you like

Origin www.cnblogs.com/jcxfighting/p/11756153.html