0

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
asked Aug 18, 2021 at 18:54
6
  • 1
    You're doing compares against the timer ID, which shouldn't change--it's an ID, not the value of the timer. There are other issues as well, but start there. Please also consider consistent indentation--it makes reading code easier. Commented Aug 18, 2021 at 18:57
  • 1
    The timerId value returned by setInterval() 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. Commented Aug 18, 2021 at 18:57
  • 3
    Also you set a click listener in a loop Commented Aug 18, 2021 at 18:59
  • 1
    You should be comparing time, not timerId. Commented Aug 18, 2021 at 19:00
  • Plus, you have two intervals running simultaneously, discarding the ID of the first. Commented Aug 19, 2021 at 8:55

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.