Ho un cronometro principale con 4 mini-cronometri per ogni passo. Dopo un tempo finito, ecco un esempio di come i timer dovrebbe guardare:Cronometro con punti di interruzione non sommati correttamente
MAIN: 00 : 14 : 57
-------------------
MINI1: 00 : 04 . 17
MINI2: 00 : 06 . 40
MINI3: 00 : 02 . 54
MINI4: 00 : 01 . 46
I mini-timer dovrebbero aggiungere fino al timer principale, come fanno in questo caso. Con il mio attuale timer, sembra sempre essere spento .02
millisecondi, quindi in questo caso si sommano a 00 : 14 . 55
anziché a 00 : 14 . 57
.
Questo è un JSFiddle dei timer correnti. Penso che il problema sia molto probabile nel file stopwatch.js
, ma non sono sicuro del motivo per cui sarebbe il caso poiché sto usando Date.now()
per calcolare quanto tempo è passato. Ecco il file stopwatch.js
che è il codice per un cronometro individuale:
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);
}
}
ho tutto del tutto all'interno del JSFiddle ho citato sopra ed anche in questo gist se questo è più facile da leggere. Qualsiasi guida sarebbe apprezzata.
Il timer restituirà risultati non corretti quando l'ora del sistema cambia o si verificano secondi bisestili, vedere https://en.wikipedia.org/wiki/Unix_time#Leap_seconds. Meglio usare 'Performance.now()' che aumenta sempre ad un tasso costante. –