微任务队列宏任务队列
- javascript是单线程,多线程都是模拟出来的,
- script、setTimeOut、setInterval是宏任务
- Promise,process.nextTick是微任务
- setTimeOut是n毫秒之后,将回调函数放入任务执行队列;setInterval是每隔n毫秒将回调函数推入任务执行队列,不能保证n毫秒之后立即执行!
- 虽然setTimeout很早就注册了,但是要等到同步任务,宏任务执行完毕才执行微任务
1
2
3
4
5
6
7
8
9
10
11
12
13setTimeout(()=>{
console.log(1)
},0)
let i =0
while(i<10000){
i++
console.log(2)
}
setTimeout(() => {
console.log(3)
}, 0)
2 1 3
再看一段复杂一点的输出1 1.1 4 2 2.11
2
3
4
5
6
7
8
9
10console.log('1');
new Promise((resolve) => {
console.log('1.1');
resolve()
}).then(() => {
console.log('2');
}).then(()=>{
console.log('2.1')
})
console.log(4)
console.log是同步任务,new Promise之后取出
1 | console.log('1'); //a同步任务,输出1 |
最后答案
1 1.2 2 3 3.1 4 5 5.1 6