宏队列与微队列
1,宏队列:用来保存 待执行的宏任务(回调),
比如:定时器回调 、DOM事件回调、ajax回调
2,微队列:用来保存待执行的微任务(回调),
比如:promise的回调、MutationObserve的回调
3,JS执行时会区别这 2个队列
JS引擎首先必须先执行所有的初始化同步任务代码
每次准备取出第一个宏任务执行前,都要将所有的微任务一个一个取出来执行
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
setTimeout(()=>{ //立即放入宏队列 console.log( 'setTimeout1' ) Promise.resolve(3).then( value => { //立即放入微队列 console.log( 'onResolved3()' , value) } ) },0) setTimeout(()=>{ //立即放入宏队列 console.log( 'setTimeout2' ) },0) Promise.resolve(1).then( value => { //立即放入微队列 console.log( 'onResolved1()' , value) setTimeout(()=>{ console.log( 'setTimeout3' , value) },0) } ) Promise.resolve(2).then( value => { //立即放入微队列 console.log( 'onResolved2()' , value) } ) |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
setTimeout(() => { console.log( "0" ) }, 0) new Promise((resolve, reject) => { console.log( "1" ) resolve() }).then(() => { console.log( "2" ) new Promise((resolve, reject) => { console.log( "3" ) resolve() }).then(() => { console.log( "4" ) }).then(() => { console.log( "5" ) }) }).then(() => { console.log( "6" ) }) new Promise((resolve, reject) => { console.log( "7" ) resolve() }).then(() => { console.log( "8" ) }) |
1 7 2 3 8 4 6 5 0