I have a main stopwatch with 4 mini-stopwatch for each step. After the end time, here is an example of what timers should look like:
MAIN: 00 : 14 : 57 ------------------- MINI1: 00 : 04 . 17 MINI2: 00 : 06 . 40 MINI3: 00 : 02 . 54 MINI4: 00 : 01 . 46
Mini timers must be added before the main timer, as in this case. With my current timer, it always seems that .02 milliseconds are off, so in this case, instead of 00 : 14 . 57 00 : 14 . 57 they will be added until 00 : 14 . 55 00 : 14 . 55 .
Here is the JSFiddle of my current timers. I think the problem is most likely in the stopwatch.js file, but I'm not sure why this would be so, since I use Date.now() to calculate how much time has passed. Here is the stopwatch.js file, which is the code for the 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 inside the JSFiddle I mentioned above, as well as in this gist , if it's easier to read. Any recommendations would be appreciated.
javascript timer stopwatch
saadq
source share