宏任务与微任务

首先执行顺序:同步任务->异步任务

异步任务又分为:宏任务与微任务。

所以整个顺序为:同步任务->微观任务->宏观任务

微观任务大概有Promise.then Object.observe MutationObserver process.nextTick(Node.js 环境)

宏观任务大概有script(整体代码) setTimeout setInterval I/O UI交互事件 postMessage MessageChannel setImmediate(Node.js 环境)

每当一个宏任务执行完之后,会检查是否有微任务,如果有,则会先执行所有微任务,再执行下一个宏任务。

题目一

setTimeout(function() {
  console.log('1')		// 宏任务
})

new Promise(function(resolve) {
  console.log('2')		// 同步任务
  resolve()
}).then(function() {
  console.log('3')		// 微任务
})

console.log('4')		// 同步任务

输出:2431

题目二

console.log('1')	
setTimeout(function() {
  console.log('2')	
  new Promise(function(resolve) {
    console.log('3')
    resolve()
  }).then(function() {
    console.log('4')
  })
})

new Promise(function(resolve) {
  console.log('5')		
  resolve()
}).then(function() {	
  console.log('6')		
})

setTimeout(function() {
  console.log('7')
  new Promise(function(resolve) {
    console.log('8')
    resolve()
  }).then(function() {
    console.log('9')
  })
})

首先执行同步任务 1 5 

再执行resolve异步微观任务6;判断是否所有微观任务都执行完了,是->执行下一个宏任务。

setTimeout宏观任务:2,3同步任务,4异步微观任务。

下一个setTimeout宏观任务:同理7,8同步任务,9异步微观任务。

所以输出结果为156234789

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值