对事件循环和任务队列的理解
- 任务队列
js中任务可以分为两种,一种是同步任务,一种是异步任务;
异步任务不进入主线程,而进"任务队列",只有"任务队列"通知主线程,某个异步任务可以执行了,该任务才会进入主线程执行;
只有主线程空了,就会去读取"任务队列";
-
在ES6中任务队列又认为"宏观任务队列","微观任务队列"
宏观任务- setTimeout, setInterval
- 解析HTML
- 修改url
- 页面加载等
微观任务
- promise
- process.nextTick等
- 事件循环(Event Loop)
- 简单来说就是主线程从"任务队列"中读取事件,这个过程是循环不断的。
- 代码演示,seTtimeout和promise结合的执行顺序
console.log('golb1');
// setTime 1 宏队列
setTimeout(function () {
console.log('timeout1');
process.nextTick(function () {
console.log('timeout1_nextTick');
})
new Promise(function (resolve) {
console.log('timeout1_promise');
resolve();
}).then(function () {
console.log('timeout1_then')
})
})
process.nextTick(function () {
console.log('glob1_nextTick');
})
new Promise(function (resolve) {
console.log('glob1_promise');
resolve();
}).then(function () {
console.log('glob1_then')
})
// setTime 2 宏队列
setTimeout(function () {
console.log('timeout2');
process.nextTick(function () {
console.log('timeout2_nextTick');
})
new Promise(function (resolve) {
console.log('timeout2_promise');
resolve();
}).then(function () {
console.log('timeout2_then')
})
})
process.nextTick(function () {
console.log('glob2_nextTick');
})
new Promise(function (resolve) {
console.log('glob2_promise');
resolve();
}).then(function () {
console.log('glob2_then')
})
结果:
golb1
glob1_promise
glob2_promise
glob1_nextTick
glob2_nextTick
glob1_then
glob2_then
timeout1
timeout1_promise
timeout2
timeout2_promise
timeout1_nextTick
timeout2_nextTick
timeout1_then
timeout2_then
-
分析:
一开始是script任务去执行。- 先执行
console.log('golb1');
- 然后遇到setTimeout 1 ,这是一个宏任务,推入宏任务队列
- 遇到nextTick 1, 这是一个微任务,推入微任务队列
- 遇到promise 1, 执行里面的
console.log('glob1_promise')
然后将then 1,推入微任务队列 - 接着又遇到了宏任务,setTimeout 2, 推入宏任务队列
- 遇到nextTick 2, 这是一个微任务,推入微任务队列
- 遇到promise 2, 执行里面的
console.log('glob2_promise')
然后将then 2,推入微任务队列 - 此时微任务队列中有 (头)nextTick1 - then1 - nextTick2 - then2 (尾)
- 调用队列中的异步任务。 执行结果: glob1_nextTick --> glob2_nextTick --> glob1_then --> glob2_then
(至于为什么会先调用nextTick, 可以访问 阮一峰老师的博客,其中有介绍nextTick)
至此第一次循环完毕了,然后开始调用宏任务队列
- 调用宏任务setTimeout 1
- 执行setTimeout 1, 输出
console.log('timeout1')
- 将nextTick3推入微任务队列
- 遇到promise 3,执行里面的
console.log('timeout1_promise')
- 将then3 推入微任务队列
(经过自己测试,我感觉是要把所有的宏任务都执行一遍,再执行里面的微任务)
- 调用宏任务setTimeout 2
执行setTimeout 2, 输出
console.log('timeout2')
重复setTimeout 1的操作此时微任务队列中应该有:
(头)nextTick3 - then3 - nextTick4 - then4调用队列中的异步任务。执行结果: timeout1_nextTick --> timeout2_nextTick --> timeout1_then --> timeout2_then
- 先执行
-
总结
可能表达的也不是很清楚,是最近面试的时候面试官问到的一些问题,"promise和setTimeout结合时候的执行顺序","事件循环"等等. 所以去搜了下这方面的资料,整理了一下。