Why is this microtask executed before macrotask in event loop?

爱⌒轻易说出口 提交于 2019-12-30 11:51:32

问题


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

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');

This outputs the following:

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

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

From MDN:

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.


回答1:


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

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.



来源:https://stackoverflow.com/questions/52019729/why-is-this-microtask-executed-before-macrotask-in-event-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!