Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!