Skip to content

Instantly share code, notes, and snippets.

@1travelintexan
Created September 13, 2023 08:00
Show Gist options
  • Save 1travelintexan/c820c17015a2cb49c41c142ea7c01e00 to your computer and use it in GitHub Desktop.
Save 1travelintexan/c820c17015a2cb49c41c142ea7c01e00 to your computer and use it in GitHub Desktop.
class Chronometer {
constructor() {
this.currentTime = 0;
this.intervalId = null;
}
start(printTimeCallback) {
this.intervalId = setInterval(() => {
this.currentTime += 1;
if (printTimeCallback) {
printTimeCallback();
}
}, 1000);
}
getMinutes() {
let currentMins = Math.floor(this.currentTime / 60);
return currentMins;
}
getSeconds() {
return this.currentTime % 60;
}
computeTwoDigitNumber(value) {
//oneliner version of solution
return ("0" + value).slice(-2);
//convert to string and then check the .length of the string
// const str = value.toString();
// if (str.length === 1) {
// return "0" + str;
// } else {
// return str;
// }
// //check the value is less than ten, then it needs a 0 in front. Else no
// if (value < 10) {
// return "0" + value.toString();
// } else {
// return value.toString();
// }
}
stop() {
clearInterval(this.intervalId);
}
reset() {
this.currentTime = 0;
}
split() {
let currentMinutes = this.getMinutes();
let currentSeconds = this.getSeconds();
let minsString = this.computeTwoDigitNumber(currentMinutes);
let secsString = this.computeTwoDigitNumber(currentSeconds);
const timeString = `${minsString}:${secsString}`;
return timeString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment