0
点赞
收藏
分享

微信扫一扫

微任务与宏任务

星河出山 2022-01-20 阅读 105

微任务与宏任务

  • 宏任务包括: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先打印

异步与同步的区别

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

使用异步的场景

  • 定时任务:setTimeout,setInverval
  • 网络请求:ajax请求,动态加载
  • 事件绑定

事件循环

1、 同步和异步任务分别进入不同的执行“场所”,同步进入主线程,
2、 异步进入Event Table并注册函数。当指定的事情完成时,
3、 Event Table会将这个函数移入任务队列(Event Queue)。
4、主线程内的任务执行完毕为空,就去任务队列(Event Queue)读取对应的函数,
5、进入主线程执行

面试真题

下面请大家看一道面试真题,说出他的执行顺序

//请写出输出内容
   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
举报

相关推荐

0 条评论