0

setInterval() Inconsistencies

I am trying to create an object that works like a stopwatch, but there is a 100 millisecond difference between Chrome and Firefox browsers. The code and test below fails in both Safari and Chrome but passes in Firefox.

Question: Why does this happen?

Questions: How to achieve Consistency with this object across browsers?

You can run this SAMPLE in several browsers and watch the test pass or fail. The sample is on JSBIN so you can also make code changes to it.

Timer Object (SUT)

I've built a Timer object that essentially works like a stopwatch:

function Timer() {
  this.interval = null;
  this.time = 0;
}

Timer.prototype.start = function () {
  var self = this;
  this.interval = setInterval(function () {
    self.time += 100;
  }, 100);
};

Timer.prototype.stop = function () {
  clearInterval(this.interval);
};

Timer Test (jasmine)

This test starts and stops the timer. It fails in Chrome but passes in FireFox.

describe("Timer", function () {

  it("should stop and record time accurately", function (done) {
    var timer = new Timer();
    timer.start();
    setTimeout(function () {
      expect(timer.time).toEqual(600);
      done();
    }, 600);
  });

});
Tabbyofjudah
  • 1,973
  • 3
  • 17
  • 29
  • 1
    there isn't much you can do to fix that. – Daniel A. White Sep 08 '14 at 19:49
  • 2
    timeouts aren't exact. they're best-effort for scheduling. you cannot hope to have perfect accuracy with them. – Marc B Sep 08 '14 at 19:50
  • 1
    If you need exact timing, then this isn't the way you're going to be able to do it. Windows, OSX and Linux are not real-time operating systems. – Matt Burland Sep 08 '14 at 19:50
  • In addition to the linked duplicate, see also [What is the reason JavaScript setTimeout is so inaccurate?](http://stackoverflow.com/questions/21097421/what-is-the-reason-javascript-settimeout-is-so-inaccurate) – apsillers Sep 08 '14 at 19:53
  • (I originally closed this as a duplicate of [Is there a more accurate way to create a Javascript timer than setTimeout?](http://stackoverflow.com/questions/196027/is-there-a-more-accurate-way-to-create-a-javascript-timer-than-settimeout), but I see that it's perhaps slightly more nuanced than that -- I think a good answer here would explain the relationship between the behaviors described in that answer and use it to explain exactly what is happening here.) – apsillers Sep 08 '14 at 20:00

1 Answers1

0

Just set this.time to 100 in object constructor if webkit and 0 if gecko.

Starmetal
  • 740
  • 6
  • 14
  • This is a good fix... but why is there a difference? webkit works consistently once the time is already set. Is there a difference in the way this function is processed between the two browsers? – Tabbyofjudah Sep 12 '14 at 21:07
  • I don't really know, but should be, while it works different. – Starmetal Sep 14 '14 at 09:37