为什么浏览器会限制 JavaScript 计时器?

Even if you’ve been doing JavaScript for a while, you might be surprised to learn that setTimeout(0) is not really setTimeout(0). Instead, it could run 4 milliseconds later:

即使你做 JavaScript 已经有一段时间了,你可能也会惊讶地发现 setTimeout(0) 并不是真正的 setTimeout(0)。相反,它可能会在 4 毫秒后运行:

1

1

2

2

3

3

4

4

5

5

const start = performance.now()

const start = performance.now()

setTimeout(() => {

setTimeout(() => {

  console.log(performance.now() - start)

  console.log(performance.now() - start)

}, 0)

}, 0)

Nearly a decade ago when I was on the Microsoft Edge team, it was explained to me that browsers did this to avoid “abuse.” I.e. there are a lot of websites out there that spam setTimeout, so to avoid draining the user’s battery or blocking interactivity, browsers set a special “clamped” minimum of 4ms.

将近十年前,我还在 Microsoft Edge 团队时,有人向我解释,浏览器这么做是为了防止“滥用”。也就是说,网上有大量网站疯狂调用 setTimeout,为了避免耗尽用户电池或阻塞交互,浏览器设定了一个特殊的“钳制”下限:4 毫秒。

This also explains why some browsers would bump the throttling for devices on battery power (16ms in the case of legacy Edge), or throttle even more aggressively for background tabs (1 second in Chrome!).

这也解释了为何某些浏览器会在设备使用电池时提高节流阈值(旧版 Edge 会调到 16 ms),或对后台标签页更激进地节流(Chrome 甚至 1 秒!)。

One question always vexed me, though: if setTimeout was so abused, then why did browsers keep introducing new timers like setImmediate (RIP), Promises, or even new fanciness like scheduler.postTask()? If setTimeout had to be nerfed, then wouldn’t these timers suffer the same fate eventually?

有个问题一直困扰我:既然 setTimeout 被滥用至此,为何浏览器还要不断推出新的计时器,比如 setImmediate已逝)、Promise,甚至更新潮的 scheduler.postTask()?如果 setTimeout 必须被削弱,这些新计时器最终难道不会遭遇同样的命运吗?

I wrote a long post about JavaScript timers back in 2018, but until recently I didn’t have a good reason to revisit this question. Then I was doing some work on fake-indexeddb, which is a pure-JavaScript implementation of the IndexedDB API, and this question reared its head. As it turns out, IndexedDB wants to auto-commit transactions when there’s no outstanding work in the event loop – in other words, after all microtasks have finished, ...

开通本站会员,查看完整译文。

inicio - Wiki
Copyright © 2011-2025 iteam. Current version is 2.146.0. UTC+08:00, 2025-09-07 01:12
浙ICP备14020137号-1 $mapa de visitantes$