简体   繁体   English

为什么 setTimeout 为 0ms 的宏任务队列比微任务队列中的任何任务都具有更高的优先级?

[英]Why macrotask queue which has setTimeout with 0ms get higher priority than any task in microtask queue?

As my understand, if both macrotask queue and microtask queue have some items ready to run, microtask get higher priority.据我了解,如果宏任务队列和微任务队列都有一些准备运行的项目,微任务将获得更高的优先级。

I'm testing my code by waiting for both queues filled up to see if this is true, but it's not the case with setTimeout 0ms.我正在通过等待两个队列都填满来测试我的代码,看看这是否属实,但 setTimeout 0ms 并非如此。 Timeout 0ms always runs first.超时 0ms 总是先运行。

If I add javascript Promise.resolve('Promise').then(displayData) , this will run first even before setTimeout 0ms如果我添加javascript Promise.resolve('Promise').then(displayData) ,这将在 setTimeout 0ms 之前首先运行

Anyone can explain why is that?任何人都可以解释为什么会这样?

 // after 3000ms: // task queue:printFoo(0ms), printHi(1ms), PrintHello(2ms) // microtask queue: displayData (about 50ms) function printHello() { console.log("hello"); } function printHi() { console.log("hi"); } function printFoo() { console.log("foo"); } function displayData(data) { console.log("data", data); } function sleep(miliseconds) { var currentTime = new Date().getTime(); while (currentTime + miliseconds >= new Date().getTime()) {} } setTimeout(printHi, 1); setTimeout(printHello, 2); setTimeout(printFoo, 0); fetch("https://jsonplaceholder.typicode.com/todos/1").then(displayData); // ~~ 50ms // Promise.resolve('Promise').then(displayData); sleep(3000);

Output: Output:

foo
data from fetch
hi
hello

The Promise returned by fetch() will only get resolved in another task, which will fire on the Networking task queue, which has lower or same priority than the Timer task queue. fetch()返回的 Promise 只会在另一个任务中得到解决,该任务将触发网络任务队列,该队列的优先级低于或等于定时器任务队列。 (See this prior answer of mine for links.) (有关链接,请参阅我之前的回答。)

Note: microtasks don't participate in the task prioritization system and are always executed as soon as they can, which in general is as soon as the JS call stack is empty.注意:微任务不参与任务优先级系统,并且总是尽快执行,通常是在 JS 调用堆栈为空时执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM