JS宏任务和微任务----2021/7/13

本文深入探讨JavaScript中的异步执行,包括宏任务(setTimeout、setInterval等)和微任务(process.nextTick、Promise.then等)的工作原理。通过示例代码解析它们在事件循环中的执行顺序,帮助开发者理解JavaScript的异步流程控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先看面试题


async function async1() {
	console.log('async1 start');
	await async2();
	console.log('asnyc1 end');
}
async function async2() {
	console.log('async2');
}
console.log('script start');
setTimeout(() => {
	console.log('setTimeOut');
}, 0);
async1();
new Promise(function (reslove) {
	console.log('promise1');
	reslove();
}).then(function () {
	console.log('promise2');
})
console.log('script end');

输出结果:

script start
async1 start
async2
promise1
script end
asnyc1 end
promise2
setTimeOut

大佬的文章:JS宏任务和微任务知识点相关

//主线程直接执行
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')
    })
})
//微事件1
process.nextTick(function() {
    console.log('6');
})
//主线程直接执行
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    //微事件2
    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')
    })
})

JS宏任务和微任务

setTimeout(() => {
   //执行后 回调一个宏事件
   console.log('内层宏事件3')
}, 0)
console.log('外层宏事件1');

new Promise((resolve) => {
  console.log('外层宏事件2');
  resolve()
}).then(() => {
  console.log('微事件1');
}).then(() => {
  console.log('微事件2')
}}

打印结果

外层宏事件1
外层宏事件2
微事件1
微事件2
内层宏事件3

  • 首先浏览器执行js进入第一个宏任务进入主线程,遇到setTimeout 分发到宏任务Event Queue中
  • 遇到 console.log()直接执行输出 外层宏事件1
  • 遇到Promise,new Promise直接执行 输出 外层宏事件2
  • 执行then被分发到微任务Event Queue中
  • 第一轮宏任务执行结束,开始执行微任务 打印‘微事件1’‘微事件2’
  • 第一轮微任务执行完毕,执行第二轮宏事件,打印setTimeout里面内容‘内层宏事件3’

宏任务

#浏览器Node
setTimeout
setInterval
setImmediate×
requestAnimationFrame×

微任务

#浏览器Node
process.nextTick×
MutationObserver×
Promise.then catch finally

宏 2
宏 4
微 3 5
宏 9
宏 10 11
微 12
1 7
微 6 8
176824359101112

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值