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
.
// 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
.
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