JS是单线程语言:顺序执行
任务队列
宏任务(macro-task):整体代码<script> setTimeout setInterval
微任务(micro-task):Promise
Promise new 之后会立即执行 之后的 then 是微任务
demo 1
setTimeout(function () { console.log('1')});new Promise(function (resolve) { console.log('2'); for (var i = 0; i < 10000; i++) { i == 99 && resolve(); }}).then(function () { console.log('3')});console.log('4');// output: 2 4 3 1
解析:
script 同步任务开始执行 当前无微任务 执行宏任务:
2 Promise new 之后会立即执行
4 同步任务 结束
3 then 是微任务
1 setTimeout 是宏任务
demo 2
console.log('1'); // 1let s1 = setTimeout(function () { console.log('2'); // 4 let p1 = new Promise(function (resolve) { console.log('3'); // 5 resolve(); }).then(function () { console.log('4') // 6 })})new Promise(function (resolve) { console.log('5'); // 2 resolve();}).then(function () { console.log('6') // 3})let s2 = setTimeout(function () { console.log('7'); // 7 let p2 = new Promise(function (resolve) { console.log('8'); // 8 resolve(); }).then(function () { console.log('9') // 9 })})// output:1 5 6 2 3 4 7 8 9
解析:
同步任务开始
1 同步任务
5 new Promise p1立刻执行 - 当前有一个微任务then 和两个宏任务 setTimeout
同步任务结束
执行EventLoop
6 then 执行微任务 - 当前还有两个宏任务 无微任务
2 3 执行第一个setTimeout - 当前还有一个宏任务(s2) 和 第一个宏任务产生的一个微任务(p1 then)
4 执行微任务(p1 then) - 当前还有一个宏任务(s2)
7 8 执行宏任务(s2) - 当前还有一个微任务(p2 then)
9 执行微任务(p2 then) 当前无任务
参考
文章转载于:https://www.jianshu.com/p/e80c4ef5a15a
原著是一个有趣的人,若有侵权,请通知删除
还没有人抢沙发呢~