JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<span id="p1"></span>
JavaScript
class Stopwatch {
constructor(placeholder) {
console.log('constructor run');
this.isRunning = false;
this.lastUpdateTime = 0;
this.totalDuration = 0;
this.placeholder = placeholder;
this.interval = null;
}
start() {
if (this.isRunning) {
return console.error("Timer is already started")
}
this.lastUpdateTime = window.performance.now();
this.isRunning = true;
this.interval = setInterval(() => {
this.totalDuration += window.performance.now() - this.lastUpdateTime;
this.lastUpdateTime = window.performance.now();
this.placeholder.innerHTML = this.totalDuration + "<br>" + this.formatTime(this.totalDuration);
}, 100) // update about every 100 ms
}
stop() {
if (!this.isRunning) {
return console.error("Timer is already stopped")
}
console.log(this.totalDuration);
this.isRunning = false;
clearInterval(this.interval);
}
reset() {
this.lastUpdateTime = 0;
this.totalDuration = 0;
this.placeholder.innerHTML = "00:00.000";
}
formatTime(ms) { return moment(ms).format('mm:ss.SSS'); }
getFormattedDuration() {
if (this.lastUpdateTime === 0) {
return "00:00.000";
}
return formatTime(this.totalDuration);
}
}
const placeholder = document.getElementById("p1");
const stopwatch = new Stopwatch(placeholder);
stopwatch.start();