js单线程的本质-------Event Loop

怎么判断是浏览器还是node环境?

node中window是未定义;setImmediate是定义的,在浏览器中未定义

timer阶段:这个阶段会执行setTimeout和setInterval

check阶段:执行setImmediate

macro task [task] 宏任务 :script(页面代码)、setTimeout、setInterval、I/O事件、UI交互事件(点击事件)

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

宏任务可以有多个队列

微任务只有一个队列

setTimeout任务之间,推迟执行的毫秒数越小,排在队列里面越靠前

在node里面,timers(setTimeout、setInterval)会优先于setImmediate

setTimeout(() => {
   console.log('setTimeout')
},0);   // 大于1000时,会先执行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中的setTimeout');
    },0);
}).then(() => {
    console.log('then');
});
console.log('end');

  

运行机制

1. 在执行栈中执行一个宏任务。 

2. 执行过程中遇到微任务,将微任务添加到微任务队列中。

3. 当前宏任务执行完毕,立即执行微任务队列中的任务。 

4. 当前微任务队列中的任务执行完毕,检查渲染,GUI线程接管渲染。 

5. 渲染完毕后,js线程接管,开启下一次事件循环,执行下一次宏任务(事件队列中取)。

猜你喜欢

转载自www.cnblogs.com/jcxfighting/p/11756153.html