I have a button where when pressed the timer starts counting down. I am having a hard time figuring out how to reset the countdown timer once that same button is pressed.
I am also wondering why my time is stopping at 0:1??
let startingCount = 5
let time = startingCount * 60
let spaceForTime = document.getElementById('countdown')
let myTimer = null
function timer() {
if (myTimer !== null) {
clearInterval(myTimer)
}
myTimer = setInterval(function timer() {
let seconds = time % 60
let minutes = Math.floor(time / 60)
seconds = seconds < 10 ? '0' + seconds : seconds
time--;
if (time >= 0) {
spaceForTime.innerHTML = `${minutes}:${seconds}`
} else if (time === 0) {
spaceForTime.innerText = "Move onto the next question!"
clearInterval(time)
}
}, 1000);
}
<div id="button">
<button onclick="timer()" id="letsChat">Let's Chat!</button>
</div>
<span id="countdown"></span>
5
Answers
You need to redeclare the
startingCount
andtime
variables ater you clear the previous interval insidetimer()
.add a check in your timer function to see if the timer is already running. If it is, clear the interval and reset the time to its starting value before starting the timer again
You have to change that in your code:
The reason the timer stops at 0:01 is because first, you set the
minutes
andseconds
variables, then you decreasetime
. You need to decrease time before setting theminutes
andseconds
variables.A few points to consider:
First, the timer isn’t resetting because you are not resetting the value of
time
(as others have mentioned).Second, The reason it stops at 0:01 is because your
time--
comes before your if conditions, so the condition is evaluatingtime == -1
on the iteration where it should show 0 second. The execution being:To resolve that, move the
time--
to the end of the interval function (aka after the if conditions).Third, your
else if
condition is never accessed since you put>=
in your if condition. It should be changed to strictly larger>
.Code with the above changes:
Note: shortened time to 6 seconds for faster demonstration