gpt4 book ai didi

javascript - Javascript 事件队列是否是一个简单的 FIFO?

转载 作者:数据小太阳 更新时间:2023-10-29 06:10:37 24 4
gpt4 key购买 nike

看看这个例子:

function A() { console.log('A'); }
function B() { console.log('B'); }
// and then i setTimeout(fn, 0) both of them
setTimeout(A, 0);
setTimeout(B, 0);

是否保证 B 会在 A 之后立即运行?
浏览器是否可能在 AB 之间的队列中添加另一个任务?

注意:AB 函数都没有向事件循环添加任何新任务。

var callbacks = [];
// then add a bunch of callbacks ... (none adds events to event queue)
//case 1:
callbacks.forEach(cb => setTimeout(cb,0))
//case 2:
setTimeout(function() {
callbacks.forEach(cb => cb());
},0);

case 1case 2 回调的执行顺序有什么不同吗?

最佳答案

Is it guarantied that B will immediately run after A?

不是立即,不是,但是保证B 将在A 之后运行。全部详情 in the spec ,但简而言之,这在 timer initialization steps 中专门解决了其中一部分说:

Wait until any invocations of this algorithm that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.

Optionally, wait a further user-agent defined length of time.

Queue the task task.

...其中 task 是调用您给 setTimeout 的回调的任务。

任务队列需要按顺序运行,因此 A 在兼容浏览器上将在 B 之前运行。

请注意,这是有保证的,因为它们由相同的方法上下文排队(请参阅规范以了解其含义的详细信息)。

Is it possible that browser add another task in the queue between A and B?

是的。浏览器可以是多线程的,并在为 AB 排队任务之间为其他事情(来自网络 worker 的消息等)排队任务.在这种情况下,您会看到 A 运行,然后是其他任务的处理程序(处理来自 web worker 的消息或其他),然后是 B

关于javascript - Javascript 事件队列是否是一个简单的 FIFO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35296875/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com