I have a main stopwatch with 4 mini-stopwatches for each step. After a finished time, here is an example of how the timers should look:
MAIN: 00 : 14 : 57
-------------------
MINI1: 00 : 04 . 17
MINI2: 00 : 06 . 40
MINI3: 00 : 02 . 54
MINI4: 00 : 01 . 46
The mini-timers should add up to the main timer, as they do in this case. With my current timer, it always seems to be .02
milliseconds off, so they would add up to 00 : 14 . 55
in this case instead of 00 : 14 . 57
.
Here is a JSFiddle of my current timers. I think the issue is most likely in the stopwatch.js
file, but I'm not sure why that would be the case since I'm using Date.now()
to calculate how much time has passed. Here is the stopwatch.js
file which is the code for an individual stopwatch:
class Stopwatch {
constructor (opts) {
this.isOn = false;
this.time = 0;
this.elem = opts.elem;
}
start () {
this.offset = Date.now();
this.interval = setInterval(() => this._update(), 10);
this.isOn = true;
}
stop () {
clearInterval(this.interval);
this.offset = null;
this.interval = null;
this.isOn = false;
}
reset () {
this.time = 0;
this._render();
}
_update () {
this.time += this._getTimePassed();
this._render();
}
_getTimePassed () {
const now = Date.now();
const timePassed = now - this.offset;
this.offset = now;
return timePassed;
}
_timeFormatter (milliseconds) {
const padZero = (time) => `0${time}`.slice(-2);
const minutes = padZero(milliseconds / 60000 | 0);
const seconds = padZero((milliseconds / 1000 | 0) % 60);
const centiseconds = padZero((milliseconds / 10 | 0) % 100);
return `${minutes} : ${seconds} . ${centiseconds}`;
}
_render () {
this.elem.textContent = this._timeFormatter(this.time);
}
}
I have everything altogether inside the JSFiddle I mentioned above and also in this gist if that's easier to read. Any guidance would be appreciated.