This works for me, but is this the right way to create this timer?
I might be naive about this but I think this is close to perfect in pure JS.
What would be the drawbacks of using this Timer compared to creating it in a different way?
- Click start and the timer starts to countdown.
- Click reset and the timer resets back to the starting time.
HTML:
<button onclick='startStopTimer()'>Start</button>
<button onclick='startStopTimer()'>Reset</button>
<h1>00:10</h1>
JavaScript:
console.clear()
let timer = document.querySelector('h1')
let startingTime = 9
let startTimer;
let startStopTimer = () => {
if(startTimer){
clearInterval(startTimer);
timer.innerHTML = '00:10'
startingTime = 9
return startTimer = undefined
}else{
return startTimer = setInterval(()=>{
timer.innerHTML = `00:0${startingTime--}`
}, 1000)
}
}
restart
vsreset
. To me,reset
means put it back to zero andrestart
means put it back to zero and start the timer again. Could just be me though. \$\endgroup\$