The problem of setTimeout minimum interval 4ms

setTimeout(()=>{console.log(5)},5)
setTimeout(()=>{console.log(4)},4)
setTimeout(()=>{console.log(3)},3)
setTimeout(()=>{console.log(2)},2)
setTimeout(()=>{console.log(1)},1)
setTimeout(()=>{console.log(0)},0)

Why did you output 1 strong 0 4ms 2 3 4 5, didn"t you say the minimum interval of 4ms ?
running environment Chrome/Safari
under Firefox, it is 0, 1, 2, 3, 4, 5

.
Mar.13,2021

// https://github.com/nodejs/node/blob/v8.9.4/lib/timers.js-sharpL456

if (!(after >= 1 && after <= TIMEOUT_MAX))
  after = 1; // schedule on next tick, follows browser behavior

set the behavior of the lowest 1ms to be in line with the browser behavior.

although there are restrictions on 4ms, there are conditions. For details, please see MDN English document

.

clipboard.png


setTimeoutsetIntervalEvent Loop;Event LoopsetTimeout

setTimeout(()=>{console.log(1)},1), console.log(1), console.log()`

:setTimeout


setTimeout4firebox0 1 5 4 3 2


:


:


chromesafari


6 setTimeout put callback functions in the task queue this time event loop , and wait for event loop to execute when the specified time is detected in the future. The callback that is pressed first will be executed first. When the next event loop is executed, if the 1ms is exceeded, execute console.log (1) first. If it does not exceed 1ms, a callback of console.log (0) is performed.


I have seen a v8 source code analysis that says that chrome's minimum implementation of timeout is 1ms, so regardless of delay settings of 1 and 0, it is as if Synchronize code executes 4ms sequentially, referring to the minimum 4ms article in the case of multi-layer timeout nesting.


the statement of minimum interval 4ms is inaccurate, or there are prerequisites. Please see HTML Standard :

.
11. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.

that is to say, if the loop is nested more than 5 layers and the delay is less than 4 Ms, it will become the 4ms
standard. I haven't personally tested how each browser defines it.


chrome is because both 1ms and 0ms are set to 1ms, so the output is 1, 0 instead of 0, 1

Source address
double intervalMilliseconds = std::max (oneMillisecond, interval * oneMillisecond);

reference article address: Event Loop specification and implementation

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1be65bc-30537.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1be65bc-30537.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?