宏任务与微任务 小例

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})

执行逻辑
首先执行主线程任务 console.log(‘1’); 输出 1
遇到setTimeout 放进宏任务执行栈 标记为setTimeout 1
遇到 process.nextTick 放进微任务执行站 标记为process1
接着new Promise 直接执行 输出7 .then放进微任务 标记then1
最后一个setTimeout 放进宏任务执行栈 标记为setTimeout 2

第一轮主线程任务 执行完毕 输出 1 7

然后开始执行微任务 process1 输出 6
然后执行微任务 then1 输出 8
第一轮微任务执行完毕 此时输出 1 7 6 8

然后第二轮宏任务setTimeout 1开始执行
console.log(‘2’) 输出2
遇到process.nextTick 放进微任务 标记process2
遇到new Promise直接执行 输出 4
.then放进微任务 标记then2
setTimeout 1里面的宏任务执行完毕

开始执行微任务process2 输出 3
then2 输出 5
第二轮宏任务setTimeout 1执行完毕 输出 2 4 3 5

然后第三轮宏任务setTimeout 2同setTimeout 1 不在赘述
最后结果 输出 1 7 6 8 2 4 3 5 9 11 10 12

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值