I have created a timer object with different timer methods, and I am fully happy how it works. However, I am unhappy with the code quality. I cannot understand how I can get the same working methods without creating additional variables, in particular the property intervalId and the function resetSecAddMin. Is it possible to have this solution working without these additional variables?
The code:
const timer = {
secondsPassed: 0,
minsPassed: 0,
intervalId: null,
startTimer() {
this.intervalId = setInterval(() => {
const resetSecAddMin = () => { this.secondsPassed = 0; this.minsPassed += 1 };
this.secondsPassed < 59 ? this.secondsPassed += 1 : resetSecAddMin();
}, [1000]);
},
getTime() {
return this.secondsPassed < 10 ? `${this.minsPassed}:0${this.secondsPassed}` : `${this.minsPassed}:${this.secondsPassed}`;
},
stopTimer() {
clearInterval(this.intervalId);
},
resetTimer() {
this.secondsPassed = 0;
this.minsPassed = 0;
},
};
I hope this question will contribute some value to the community. I believe that writing a readable code is not less important than creating working solutions.
You actually don't need any timer. On startTimer() method you record start time this.startTime = Date.now(). And then inside getTime() you get the delta in milliseconds var delta = Date.now() - this.startTime. It will be in milliseconds, but you can divide by 1000 to get seconds and figure out minutes too by division.