Minimum Timer Delay and Reliability(JavaScript计时器的最小时间延迟和可靠性)
While it's pretty obvious that you can have timer delays of seconds, minutes, hours - or whatever large interval you desire - what isn't obvious is the smallest timer delay that you can choose.
At a certain point a browser is simply incapable of providing a fine-enough resolution on the timers in order to handle them accurately (since they, themselves, are restricted by the timings of the operating system). Across most browsers, however, it's safe to say that the minimum delay interval is around 10-15ms.
We can come to that conclusion by performing some simple analysis upon the presumed timer intervals across platforms. For example if we analyze a setInterval
delay of 0ms we can find what the minimum delay is for most browsers.
OSX Browsers:
From Top Left: Firefox 2, Safari 3, Firefox 3, Opera 9.
Windows Browsers:
From Top Left: Firefox 2, Internet Explorer 6, Firefox 3, Opera 9
In the above charts the lines and numbers indicate the number of simultaneous intervals being executed by the browser.
We can come to some conclusions: Browsers all have a 10ms minimum delay on OSX and a (approximately) 15ms delay on Windows. We can achieve either of those values by providing '0' (or any other number below 10ms) as the value to the timer delay.
There is one catch, though: Internet Explorer is incapable of providing a 0ms delay to asetInterval
(even though it'll happily work with a setTimeout
). Whenever a 0ms delay is provided the interval turns into a single setTimeout
(only executing the callback once). We can get around this by providing a 1ms delay instead. Since all browsers automatically round up any value below their minimum delay using a 1ms delay is just as safe as effective using 0ms - only moreso (since Internet Explorer will now work).
There's some other things that we can learn from these charts. The most important aspect is simply a reinforcement from what we learned previously: browsers do not guarantee the exact interval that you specify. Browsers like Firefox 2 and Opera 9 (on OSX) have difficulties providing a reliable timer execution rate. A lot of this has to do with how browsers perform garbage collection on JavaScript (the significant improvement that was made in Firefox 3 in JavaScript execution and garbage collection is immediately obvious in these results).
So while very small delay values can be provided by a browser the exact accuracy is not always guaranteed. This needs to be taken into account in your applications when using timers (if the difference between 10ms and 15ms is problematic then you might have to re-think how your application code is structure).