Skip to content

Instantly share code, notes, and snippets.

@josecarneiro
Created May 21, 2021 15:23
Show Gist options
  • Save josecarneiro/f22db3408198f13a1f8aeb9e35efdb11 to your computer and use it in GitHub Desktop.
Save josecarneiro/f22db3408198f13a1f8aeb9e35efdb11 to your computer and use it in GitHub Desktop.
class Chronometer {
constructor() {
this.currentTime = 0;
this.intervalId = null;
}
start(callback) {
this.intervalId = setInterval(() => {
this.currentTime++;
if (callback) callback();
}, 1000);
}
getMinutes() {
return Math.floor(this.currentTime / 60);
}
getSeconds() {
return this.currentTime % 60;
}
computeTwoDigitNumber(value) {
return value < 10 ? '0' + value : String(value);
}
stop() {
clearInterval(this.intervalId);
}
reset() {
this.currentTime = 0;
}
split() {
const minutes = this.computeTwoDigitNumber(this.getMinutes());
const seconds = this.computeTwoDigitNumber(this.getSeconds());
return `${minutes}:${seconds}`;
}
}
// The following is required for our automated tests, ignore it for now.
if (typeof module !== 'undefined') module.exports = Chronometer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment