js的执行是通过队列实现的
同步任务
首先是同步任务队列(例如console.log(“输出”))由其顺序依次先执行。
异步任务
其次是异步任务 异步任务分为宏任务和微任务,js将所有任务都放入其对应的任务队列,然后先执行微任务队列(promise),执行完后再执行宏任务队列(setTimeout)(队列是先进的先出) ,若微任务中有宏任务会继续放入队列中。
/*
* 1.先输出同步任务 0 1
* 2.继续执行 宏任务 set1 set3
* 3.进入宏任务set1 同步任务 5 微任务 res()
* 4.进入res 同步任务 2 宏任务 set2 将set2 存入宏任务队列(set3 set2)
* 4。 执行set3 同步任务 3 , 再执行 set2 同步任务 4
* */
new Promise(res=>{
console.log(0)
setTimeout(()=>{ // set1
res()
console.log(5)
})
}).then(()=>{
console.log(2)
setTimeout(()=>{ // set2
console.log(4)
})
})
setTimeout(()=>{ // set3
console.log(3)
})
console.log(1)
// 0 1 5 2 3 4