Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
How to clear interval with a btn if it's already set

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}`
} 
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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
  })
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda