Working on making a 2 minute timer in JS. I'm new so please bear with me. I want to make the timer so that when you click the button (I already made the button in js), it decrements the time from 2 minutes. Here is what I have so far. The code doesn't go down second by second. Any suggestions would be helpful, thank you!
const startingMinutes = 2
let time = startingMinutes * 60
let timerId = setInterval(countDown, 1000)
function countDown() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
time--
if (timerId <= -startingMinutes) {
countdown.innerHTMl = 'Good Luck!'
clearInterval(timerId)
}
if (timerId <= 0) {
countdown.innerHTML = 'Time is up!'
clearInterval(timerId)
}
button.addEventListener('click', () => {
countDown()
countdown.innerHTML = minutes + ' minutes ' + ': ' + seconds + ' seconds '
})
}
timerId = setInterval(countDown, 1000)
Barmar
789k57 gold badges555 silver badges669 bronze badges
1 Answer 1
This work successfully:
const startingMinutes = 0.25
let time = startingMinutes * 60
let timerId = setInterval(countDown, 1000)
function countDown() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
time--
console.log(minutes, 'minutes:', seconds, 'seconds');
if (time <= 0) {
console.log('Time is up!');
clearInterval(timerId)
}
}
Then, just call setInterval with countDown function in your click handler
answered Aug 18, 2021 at 19:19
wowandy
1,3222 gold badges16 silver badges27 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
timerIdvalue returned bysetInterval()has nothing at all to do with the interval time; it's a numeric id for the timer and it really does not mean anything.time, nottimerId.