当前位置: 代码迷 >> 综合 >> // Event Loop/事件循环/事件环(5)
  详细解决方案

// Event Loop/事件循环/事件环(5)

热度:39   发布时间:2023-12-03 05:30:01.0

1.关于事件循环的回答 

 1. JS 代码的执行分为同步代码(任务)和异步代码(任务:微任务=> Promise.then、MutationObserver + 宏任务 => 定时器)

2.当碰到同步代码时直接执行栈中执行

3.当碰到异步并且时机符合时(列如定时器时间到了,例如AJAX请求你发起了...),就会把异步的代码添加到任务队列当中

4.【当执行栈中同步代码执行完毕后,就去任务队列中把异步任务拿带执行栈中执行】、

5.这种反复执行任务队里的操作就是Event Loop(事件循环)

2.例题

1.试题1

       setTimeout(function () {console.log(1)}, 0);new Promise(function executor(resolve) {console.log(2);for (var i = 0; i < 10000; i++) {i == 9999 && resolve();}console.log(3);}).then(function () {console.log(4);});console.log(5);

思路:先执行同步的任务,打印出2,3,5 ,剩下的就是异步任务了,定时器属于异步任务中的宏任务,// 当等于 9999,由于调用了 resolve,所以会把后面的 then 添加到任务队列属于微任务,

先执行完微观任务后在去执行宏观,所以依次打印4,1,结果为,2,3,5,4,1。

2.试题2

    setTimeout(() => {new Promise(resolve => {resolve();}).then(() => {console.log('test');});console.log(4);});new Promise(resolve => {resolve();console.log(1)}).then(() => {console.log(3);Promise.resolve().then(() => {console.log('before timeout');}).then(() => {Promise.resolve().then(() => {console.log('also before timeout')})})})console.log(2);

思路: 先执行同步任务   第一轮打印出  1,2 , 微任务分为定时器 和 promise中的,打印3,before timeout,also before timeout, 打印完毕后,在执行宏任务, 定时器中的同步任务打印 4,和定时器中的微任务test,综上描述打印出的结果是:1,2,3,before timeout,also before timeout,4,test。

  相关解决方案