I found myself on this jsperfs' page, why does that happen?
Any clues? And why is 4 faster than 0 too?
I found myself on this jsperfs' page, why does that happen?
Any clues? And why is 4 faster than 0 too?
There is a comment about this, you should read the article closely.
Info
The smallest setTimeout timeout value allowed by the HTML5 specification is 4 ms. Smaller
values should clamp to 4 ms.
Therefore, the first two tests below should have about the same result.
P.S. Some browsers freak out when you use a value greater than 599147937791 for the
timeout (i.e. they use 0 or 4 ms instead), hence the last test.
Essentially, Javascript has internal handling for 0
and 599147937792
as they qualify for over/underflow values for setTimeout
and they are rounded to a default minimum accepted value 4
ms. This is probably because it is unreasonable to ask for a 0
ms delay as it would probably take longer than this to even process the function and determine this is what the user wants. The error on the larger value is probably due to the fact that computers have limits how big/small of a number that you can represent.
To understand why the large and small values return after 4
for example is that the internal handling takes time as well, a very small amount, but time. Consider these two timelines:
Timeline 1
setTimeout(...,0)
is calledif (time < 4) {// use 4}
)0 -> 4
.4
msTimeline 2
setTimeout(...,4)
is calledif (time < 4) {// use 4}
)4
msStep 3 in the two timelines takes longer in the first case as there is the extra step of changing the value. Both will wait for the same amount of time, but the second one will start its timing ever so slightly sooner. This is much the same with 599147937792
, except the check will be for the upper bound.
The phrasing "freaks out"
makes me think it might look more like
try {
// try with the given input
} catch (Exception) {
// Ahh I freaked out, just use 4 instead!!!!111!!!
}