gpt4 book ai didi

javascript - 棘手的 setTimeout 序列

转载 作者:行者123 更新时间:2023-11-30 16:49:19 25 4
gpt4 key购买 nike

一组 setTimeout 调用,间隔为 0,1,2,3。

function f() {

setTimeout(function a() {console.log(10);}, 3);

setTimeout(function b() {console.log(20);}, 2);

setTimeout(function c() {console.log(30);}, 1);

setTimeout(function d() {console.log(40);}, 0);

}

f();

输出:(来自 chrome。希望在其他浏览器中也一样)

30

40

20

10

谁能解释清楚为什么顺序不是 30、40、10、20?据说浏览器保持至少 10 毫秒或(规范说)4 毫秒的间隔。如果是这样,请使用时间指标或任何便于解释此行为的指标来验证输出。为了理解该语言的这一令人敬畏的特性,我错过了什么细节?

编辑:

我知道这些函数是异步的。我读过 John Resig 的博客好几遍。而且我知道 setTimeout' 回调不能保证在指定的时间间隔内执行。

更准确地说,我希望有一个解释可以解释执行队列、事件循环、调用堆栈和计时器方面的行为。

最佳答案

In order to understand how the timers work internally there’s one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there’s been an opening in the execution.

引用thisthis了解更多详情

关于javascript - 棘手的 setTimeout 序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30759861/

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