js宏任务和微任务

宏任务和微任务

宏任务包括:setTimeout setInterval Ajax DOM事件
微任务:Promise async/await
注意:微任务比宏任务的执行时间要早
console.log(100);

setTimeout(()=>{
    console.log(200);
})

setTimeout(()=>{
    console.log(201);
})

Promise.resolve().then(()=>{
    console.log(300);
})

console.log(400);

// 100 400 300 200 201
// 为什么300比200先打印
异步与同步的区别

异步不会阻塞程序的执行
同步会阻塞程序的执行

使用异步的场景
1.定时任务:setTimeout,setInverval
2.网络请求:ajax请求,动态<img>加载
3.事件绑定
事件循环
同步和异步任务分别进入不同的执行“场所”,同步进入主线程,
异步进入Event Table并注册函数。当指定的事情完成时,
Event Table会将这个函数移入任务队列(Event Queue)。
主线程内的任务执行完毕为空,就去任务队列(Event Queue)读取对应的函数,
进入主线程执行
面试真题

执行顺序

//请写出输出内容
   async function async1() {
       console.log('async1 start');
       await async2();
       console.log('async1 end');
   }
   async function async2() {
       console.log('async2');
   }
   
   console.log('script start');
   
   setTimeout(function() {
       console.log('setTimeout');
   }, 0)
   
   async1();
   
   new Promise(function(resolve) {
       console.log('promise1');
       resolve();
   }).then(function() {
       console.log('promise2');
   });
   console.log('script end');

输出结果为:

// 首先执行同步的 在执行异步
// promise是同步的,但是里的四个api是异步的
// async await 也是同步的 但是会先执行调用的 在执行下面的代码
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值