事件循环相关

面试中被问到的一段代码

setTimeout(function(){
	setTimeout(function(){
		console.log(1);
	}, 100);
	new Promise(resolve => {
		console.log(2);
		resolve(3);
		setTimeout(function(){
			console.log(4);
		}, 1);
	}).then((number) => {
		console.log(number)
	})
	console.log(6);
}, 0);

setTimeout(function(){
	console.log(7);
}, 100);

console.log(8);

// 8 2 6 3 4 7 1

噗,开始还纳闷4为啥在7前面,后来仔细一看delay就傻了。

这里找到两个相关题目

let count = 0
setTimeout(() => {
    console.log('1 setTimeout')
}, 0)
const i = setInterval(() => {
    console.log('2 setInterval')
    count++
    if (count === 5) {
        clearInterval(i)
    }
    setTimeout(() => {
        console.log('3 setTimeout ', count)
    }, 0)
}, 0)
setTimeout(() => {
    console.log('4 setTimeout')
}, 0)
// 1 2 4 2 3 2 3 2 3 2 3 3 
  1. async await
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');

 //script start
 //async1 start
 //async2
 //promise1
 //script end
 //async1 end
 //promise2
 //setTimeout

解释:https://www.cnblogs.com/lpggo/p/8127604.html
!!!!!!这个链接里要注意:实际运行链接中的两段代码输出没有区别

本人的总结理解(母鸡对不对):

  • async 函数中可能会有 await 表达式,async 函数执行时,如果遇到 await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行并返回解析值。
  • 有了await之后,先执行await,再执行promise.then()和主线程,再执行await后面的语句
    因为await会让出线程就会去执行后面的
  • 等本轮事件循环执行结束后,又会跳回到async函数中(test函数),等待之前await 后面表达式的返回值
  • 宏任务总是最后执行

Event Loop 的循环过程:

  • 执行一个宏任务(一般一开始是整体代码(script)),如果没有可选的宏任务,则直接处理微任务
  • 执行过程中如果遇到微任务,就将它添加到微任务的任务队列中
  • 执行过程中如果遇到宏任务,就将它添加到宏任务的任务队列中
  • 执行一个宏任务完成之后,就需要检测微任务队列有没有需要执行的任务,有的话,全部执行,没有的话,进入下一步
  • 检查渲染,然后 GUI 线程接管渲染,进行浏览器渲染
  • 渲染完毕后,JS线程继续接管,开始下一个宏任务…(循环上面的步骤)

注意:一般都是微任务先执行,然后再执行宏任务,但是在promise里面的宏任务函数,必须先执行完,才能往下执行其它宏任务(promise里面的宏任务也是在微任务执行完毕才执行哦,只不过是在宏任务队列里面先执行)

辛酸😔

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值