How to clear interval with a btn if it's already set

Viewed 39

So I'm currently very new to JavaScript and it's concepts and am trying to make a game where there are 4 btns which start a timer, then reset it and start it again when either of them are pressed the second time, but whenever I press any button twice it speeds up the timer 2x instead of resetting and starting it again

This is my code, apologies if it's is messy and/or hard to understand

let time = 5
const countDown = document.querySelector('#countdown')
let challenge = document.getElementById('text')
const btns = document.querySelectorAll('.btn')
let text = ''

function randomText(){
  return Math.floor(Math.random() * arr.length)
}

btns.forEach(function(btn){
  btn.addEventListener('click', function(e){
    time = 5
    const timer = setInterval(countdown, 1000)
    text = arr[randomText()]
    challenge.textContent = text
  })
})



function countdown(){
  if( time === 0 ){
    time = 5
}
  time--
  countDown.innerHTML = `00:0${time}`
} 
1 Answers
let timer;
btns.forEach(function(btn){
  btn.addEventListener('click', function(e){
    time = 5
    clearInterval(timer);
    timer = setInterval(countdown, 1000)
    text = arr[randomText()]
    challenge.textContent = text
  })
})
Related