为什么在事件循环中在宏任务之前执行此微任务? [英] Why is this microtask executed before macrotask in event loop?

查看:276
本文介绍了为什么在事件循环中在宏任务之前执行此微任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,在每个宏任务之后 处理完整的微任务任务队列。

My understanding is that the full microtask task queue is processed after each macrotask.

如果是这种情况,为什么<在 JavaScript Promise 微任务之后,将执行code> setTimeout 回调c>?

If that is the case, why does the setTimeout callback get executed after the Promise microtasks in the following snippet of JavaScript?

console.log('start');

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

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

console.log('end');

这将输出以下内容:

> "start"
> "end"
> "promise"
> "setTimeout"

是因为〜 4ms 现代浏览器带来的延迟?

Is it because of a ~4ms delay imposed by modern browsers?

来自 MDN


在现代浏览器中,当由于$ b $而触发连续调用时,setTimeout() / setInterval()调用至少每4ms被限制为
a一次b回调嵌套(嵌套级别至少为某个
深度),或者在一定数量的连续间隔之后。

In modern browsers, setTimeout()/setInterval() calls are throttled to a minimum of once every 4ms when successive calls are triggered due to callback nesting (where the nesting level is at least a certain depth), or after certain number of successive intervals.



Though this states that it is only true for successive callback nesting.

推荐答案


我的理解是,在每个宏任务执行完后,将处理完整的微任务任务队列。

My understanding is that the full microtask task queue is processed after each macrotask.

是。以及您运行的代码,从 console.log('start') console.log('end')就是这样的宏任务。运行完毕后,将处理带有promise回调的微任务队列,只有在下一个宏任务(超时)开始运行之后。

Yes. And the code that you ran, from console.log('start') to console.log('end'), is such a macrotask. After it ran to completion, the microtask queue with the promise callbacks is processed, and only after that the next macrotask (the timeout) gets to run.

这篇关于为什么在事件循环中在宏任务之前执行此微任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆