It seems that when I setInterval
for 1000ms, it actually fires the function every 1001ms or so. This results in a slow temporal drift the longer its running.
var start;
var f = function() {
if (!start) start = new Date().getTime();
var diff = new Date().getTime() - start;
var drift = diff % 1000;
$('<li>').text(drift + "ms").appendTo('#results');
};
setInterval(f, 1000);
When run this shows the inaccuracy immediately.
- 0ms
- 1ms
- 2ms
- 3ms
- 4ms
- 5ms
- 5ms
- 7ms
- 8ms
- 9ms
- 9ms
- 10ms
See it for yourself: http://jsfiddle.net/zryNf/
So is there a more accurate way to keep time? or a way to make setInterval
behave with more accuracy?
setInterval
account for elapsed time in the function before scheduling the next? – DiellesetInterval
does attempt to account for function run time: jsfiddle.net/zryNf/8 – Dielle