JavaScript中宏任务和微任务

JavaScript把任务分为同步任务和异步任务,异步任务又被进一步划分为宏任务和微任务。

宏任务:

1.异步Ajax请求

2.setTimeOut,setIternal

3.文件操作

微任务:

1.promise.then,.catch,和.finally

2.process.nextTick

宏任务和微任务是交替执行的。

每一个宏任务执行完后都会检查是否存在待执行的微任务,如果有,则执行完所有微任务后,在执行下一个宏任务。

代码示例与运行1:

setTimeout(function(){
  console.log('1')
})
new Promise(function(resolve){
  console.log('2')
  resolve()
}).then(function(){
  console.log('3')
})
console.log('4')//运行结果:
//2
//4
//3
//1

只要new一个promise的实例,后面的function会立马被执行,所以4,5,6行代码属于同步任务,输出2。另外,最后一行输出4。.then被加入微任务队列,计时器被加入宏任务队列。

同步任务:输出2,4

异步任务:先执行微任务输出3,再执行宏任务输出1

所以最后输出结果为2431.

代码示例与运行2:

1 console.log('1')

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

11 new Promise(function(resolve){
12 console.log('5')
13  resolve()
14 }).then(function(){
15  console.log('6')
16 })

17 setTimeout(function(){
18  console.log('7')
19 new Promise(function(resolve){
20  console.log('8')
21  resolve()
22 }).then(function(){
23  console.log('9')
24 })
25 })

运行结果为:156234789

分析:首先执行同步任务输出1和5,执行完11,12,13行代码后,14,15行加入微任务执行队列,同步任务执行完后,再执行微任务队列中的微任务输出6,清空微任务队列。之后执行宏任务(2到10行代码),执行其中的同步任务,输出2和3。把第7,8行代码放入微任务执行队列,在执行下一个宏任务之前,执行微任务队列中的任务,输出4。同理输出7,8,9.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值