Core Viewpoint - The article discusses the behavior of JavaScript's setTimeout function, highlighting that it does not execute with a true delay of 0 milliseconds, but rather has a minimum delay of approximately 4 milliseconds due to browser limitations aimed at preventing abuse and ensuring user experience [6][8].   Group 1: Timer Behavior and Limitations - Browsers impose a minimum delay of 4 milliseconds for setTimeout to prevent excessive battery drain and maintain page interactivity [8]. - Different browsers have varying restrictions, with older versions of Edge increasing the delay to 16 milliseconds on battery-powered devices, and Chrome imposing a 1-second delay on background tabs [8]. - A benchmark test showed that setTimeout in Chrome took 4.2 milliseconds, while alternatives like MessageChannel and scheduler.postTask performed significantly better [10][11].   Group 2: Alternatives to setTimeout - The article evaluates alternatives to setTimeout, including setImmediate, MessageChannel.postMessage, window.postMessage, and scheduler.postTask, with the latter being recommended for its ease of use and performance [9][11]. - The benchmark results indicated that scheduler.postTask and MessageChannel.postMessage had comparable performance, while setTimeout was consistently slower across different browsers [10][11].   Group 3: Developer Responsibility and Browser Design - There is a debate within the industry regarding whether developers should be held accountable for their code or if browsers should impose restrictions to prevent misuse of APIs like setTimeout [12]. - The article suggests that providing developers with better tools for task scheduling could reduce reliance on setTimeout and the need for browser interventions [12][13]. - The existence of the Scheduler API indicates a shift towards empowering developers while aligning with browser rendering processes [13].
为什么 setTimeout(0) 不是真的 0 毫秒?浏览器藏了这些“小心思”
 程序员的那些事·2025-09-14 11:04