当前位置: 首页 > article >正文

宏任务和微任务+超全面试真题(持续更新ing

概念

微任务和宏任务是在异步编程中经常使用的概念,用于管理任务的执行顺序和优先级。

  • 宏任务:setTimeout, setInterval,I/O 操作和 UI 渲染等。
  • 微任务: Promise 回调、async/await等

微任务通常比宏任务具有更高的优先级。

执行情况

  1. 微任务会在当前宏任务执行完毕后立即执行,而宏任务则需要等待当前宏任务执行完毕后,再从宏任务队列中选择下一个宏任务执行。
  2. 微任务(Microtask) 总是在所有的 宏任务(Macrotask) 之前执行。

当一个宏任务执行完毕后,JavaScript 引擎会立即检查微任务队列,并执行所有微任务。微任务队列为空后,引擎才会继续执行下一个宏任务。

好处:
保持状态一致性:在执行微任务时,保证了所有相关的异步操作在同一个宏任务执行周期内完成。这有助于在执行下一个宏任务之前,确保应用状态的一致性和数据的完整性。

具体执行顺序

  1. 当执行脚本开始时,会先执行一个宏任务(通常是脚本本身)。
  2. 执行完当前宏任务后,检查微任务队列。
  3. 如果微任务队列不为空,则按照先进先出的顺序依次执行所有微任务,直到微任务队列为空。这意味着微任务会在下一个宏任务之前执行。
  4. 当前宏任务执行完毕后,浏览器会渲染页面更新UI。
  5. 检查是否有新的宏任务进入事件队列。如果有,则选择最早进入队列的宏任务,并执行它。如果队列为空,则继续等待新的宏任务进入队列。
    重复步骤2-5,循环执行宏任务和微任务。

面试题

题目1

console.log('1');

setTimeout(function() {
  console.log('2');
}, 0);

Promise.resolve().then(function() {
  console.log('3');
});

console.log('4');

输出:1 4 3 2
首先打印了数字1和4,这是因为它们是同步任务。然后,微任务Promise的回调函数被添加到微任务队列中。接下来,通过setTimeout函数创建的定时器被添加到宏任务队列中。当JavaScript引擎处于空闲状态时,它会先执行微任务队列中的任务,然后再执行宏任务队列中的任务。

所以,数字3首先被打印,这是因为微任务具有更高的优先级,它会在当前任务完成后立即执行。然后,数字2被打印,这是因为宏任务需要等待一段时间,直到JavaScript引擎空闲时才会执行。

题目2

console.log('script start');

setTimeout(() => {
  console.log('setTimeout'); // 宏任务
}, 0);

Promise.resolve().then(() => {
  console.log('promise1'); // 微任务
}).then(() => {
  console.log('promise2'); // 微任务
});

console.log('script end');

在这里插入图片描述

题目3

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  console.log("async2");
}
console.log("script start");
async1();
console.log("script end");
// 输出顺序:
// script start
// async1 start
// async2
// script end  !!
// async1 end  !! 容易错

await async()后面的代码相当于是在.then里面执行的,所以会先执行 script end
在这里插入图片描述

题目4

console.log("Start");

    new Promise((resolve) => {
      console.log("Inside Promise");
      resolve();
    }).then(() => {
      console.log("Promise then");
    });

    console.log("End");

在这里插入图片描述

Promise 的回调(即 .then、.catch、.finally 里的函数)会被添加到微任务队列中,注意不是Promise的参数

题目5

console.log('Start');

async function asyncFunc() {
  console.log('Inside async function');
  await new Promise((resolve) => {
    console.log('Inside Promise');
    resolve();
  });
  console.log('After await');
}

asyncFunc();

console.log('End');

在这里插入图片描述

题目6

  console.log("Start");

    async function asyncFunc() {
      console.log("Inside async function");
      await new Promise((resolve) => {
        console.log("Inside Promise");
        resolve();
      }).then((res) => {
        console.log("then");// 注意这里
      });
      console.log("After await");
    }

    asyncFunc();

    console.log("End");

+

题目7

初创外企的面试题

 const printing = () => {
    console.log('A');
    setTimeout(() => { console.log('B'); }, 1000);
    setTimeout(() => { console.log('C'); }, 0);
    console.log('D');
    console.log('E');
    }

    printing();

A D E C B

题目8

 console.log(1);  // 
 
    setTimeout(() => {
      console.log(2);  //
    });

    const p1 = new Promise((reslove) => {
      console.log(3); //
      reslove();
    });

    p1.then(() => {
      console.log(4); //
    });

    console.log(5); //

    const p2 = new Promise((reslove) => {
      console.log(6);  //
      reslove();
    });

    p2.then(() => {
      console.log(7);  //
    });

    // 1 3 5 6 4 7 2

注意setTime是宏任务,所以排到后面了

题目9

    function testAsy(x) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(x);
        }, 3000);
      });
    }
    async function testAwt() {
      let result = await testAsy("hello world");
      console.log(result); // 3秒钟之后出现hello world
      console.log("cuger"); // 3秒钟之后出现cug
    }
    testAwt();
    console.log("cug"); //立即输出cug

题目10

   console.log("script start");
    let promise1 = new Promise(function (resolve) {
      console.log("promise1");
      resolve("resolve!"); // 注意这里
      console.log("promise1 end");
    }).then(function (res) {
      console.log("promise2");
      console.log(res); // 注意这里
    });
    setTimeout(function () {
      console.log("settimeout");
    });
    console.log("script end");

在这里插入图片描述

题目11

    console.log("start");

    setTimeout(() => {
      console.log("1");

      new Promise((resolve) => {
        console.log("2");

        resolve();
      }).then(() => {
        console.log("3");
      });

      new Promise((ressolve, reject) => {
        console.log("middle");
        reject();
      })
        .then(() => {
          console.log(4);  // 注意这里!!
        })
        .catch(() => {
          console.log("5");
          setTimeout(() => {
            console.log("6");
          });
        });
    });

    console.log("end");

在这里插入图片描述


http://www.kler.cn/news/307622.html

相关文章:

  • 【Elasticsearch系列六】系统命令API
  • Android DPC模式多开 APP
  • 安全区域边界等保测评
  • 安全隔离上网的有效途径:沙盒
  • QT开发:深入详解QtCore模块事件处理,一文学懂QT 事件循环与处理机制
  • SQL使用IN进行分组统计时如何将不存在的字段显示为0
  • CISP-PTE CMS sqlgun靶场渗透测试
  • 学习笔记 韩顺平 零基础30天学会Java(2024.9.16)
  • 神经网络_使用tensorflow对fashion mnist衣服数据集分类
  • uniapp js修改数组某个下标以外的所有值
  • 2024.09.08 校招 实习 内推 面经
  • python Open3D 验证安装崩溃
  • 论文内容分类与检测系统源码分享
  • String 72变 ---------各种字符串处理方法
  • WSL挂载U盘或移动硬盘
  • 一起对话式学习-机器学习02——机器学习方法三要素
  • Apache-wed服务器环境的安装
  • 智能工厂的设计软件 单一面问题分析方法的“独角兽”程序
  • JVM面试真题总结(七)
  • 总结对象相关知识
  • Go语言并发编程之select语句详解
  • 【相机方案(2)】V4L2 支持相机图像直接进入GPU内存吗?DeepStream 确实可以将图像数据高效地放入GPU内存进行处理!
  • 后端开发刷题 | 打家劫舍
  • gin基本使用
  • 30款免费好用的工具,打工人必备!
  • 基于Keil软件实现实时时钟(江协科技HAL库)
  • Java-数据结构-二叉树-基础 (o゚▽゚)o
  • 代码随想录训练营Day3 | 链表理论基础 | 203.移除链表元素 | 707.设计链表 | 206.反转链表
  • Flink学习2
  • 力扣每日一题