0

I am trying to use $timeout (or $interval) and from the docs and numerous examples on the web counting in 1 second increments is easy:

var counter = 0;
$timeout(timer(), 1000);

var timer = function() {
    counter++;
    $timeout(timer(), 1000);
};

When calling $timeout with 1 millisecond increments, however, the time is not accurate. Here is an example: http://jsfiddle.net/eh8o9s28/

If you run the timer in the example it looks OK, but compare to a stopwatch and after about 20 seconds the Angular time is about 2 seconds wrong, and it continues to diverge from there. (Note that if you change the increment to 1000, the time is perfectly accurate.)

Any ideas? I am wondering whether millisecond increments is too fast for the $digest cycle to keep up with?

markau
  • 854
  • 8
  • 21

1 Answers1

1

$timeout is jus a wrapper for setTimeout timing functions in JS are highly unreliable, they are approximate at best, their precision depends on many factors like OS, architecture, CPU load, and even on how well is your scrip built, so you shouldn't count on $timeout or $interval for time critical operations if high precision is required

Dayan Moreno Leon
  • 5,357
  • 2
  • 22
  • 24
  • Ok, that's good to know (although disappointing). It seems the answer is to use Date() functions to calculate the time. http://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout/196138#196138 – markau Jan 18 '15 at 01:27