sunflowers14
sunflowers14

Reputation: 1

Javascript Counter Troubleshooting

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)

Upvotes: 0

Views: 61

Answers (1)

wowandy
wowandy

Reputation: 1302

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

Upvotes: 1

Related Questions