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

169
Visualizações
Counter speed increases when the start button is clicked again

When the start button is clicked once, everything works perfectly fine. However, when the start button is clicked multiple times (by accident for example), the speed of the counter increases and the stop button doesn't seem to work any more!

Why is this happening? And what can I do to prevent the start button (if clicked accidentally) from increasing the speed of the timer when it is already running?

<button id="startBtn" onclick="startTimer()">Start</button>
    <button id="stopBtn" onclick="stopTimer()">Stop</button>
    <h2 id="timer"></h2>
    <script>
        let myCounter
        function startTimer() {
            myCounter = setInterval(counter, 200);
        }
        function stopTimer() {
            clearInterval(myCounter);
        }
        let i = 0;
        function counter() {
            document.getElementById("timer").innerHTML = i++;
        }
    </script>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Welcome to StackOverflow.

Within your question, it's unclear if you want the timer to reset if the user clicks the start button again, however with my answer, I came to the conclusion that you didn't.

Here's a modified version of startTimer() which utilizes a guard clause to check if an interval already exists (and if so, don't start again)

function startTimer() {

    // Guard clause! If the counter exists, exit the function!
    if(myCounter) {
        return
    }

    myCounter = setInterval(counter, 200);
}

A tiny update of the stop function is also needed to set myCounter to null after the counter is stopped:

function stopTimer() {
    clearInterval(myCounter);
    // Set the counter to Null, because it is still declared even though it has no value! (try removing this line and see what happens when you hit start again)
    myCounter = null;
}

Hope this helped :)

about 4 years ago · Juan Pablo Isaza Relatório

0

I added a variable that can helps you detect if the counter is already clicked or not, with the condition of that variable, you can have what you want, I edited your code.

<button id="startBtn" onclick="startTimer()">Start</button>
    <button id="stopBtn" onclick="stopTimer()">Stop</button>
    <h2 id="timer"></h2>
    <script>
        let myCounter
        let clicked = false;
        function startTimer() {
            if(!clicked){
                myCounter = setInterval(counter, 200);
            }
            clicked = true;
        }
        function stopTimer() {
            if(clicked){
              clearInterval(myCounter);
            }
            clicked = false;
        }
        let i = 0;
        function counter() {
            document.getElementById("timer").innerHTML = i++;
        }
    </script>

about 4 years ago · Juan Pablo Isaza Relatório

0

You could simply disable the start button once clicked, and re-enable it when the stop button is clicked.

let i = 0;
let myCounter;

let startBtn = document.getElementById('startBtn');
let stopBtn = document.getElementById('stopBtn');
let timer = document.getElementById('timer');

function startTimer() {
  startBtn.disabled = true;
  stopBtn.disabled = false;
  myCounter = setInterval(counter, 200);
}

function stopTimer() {
  startBtn.disabled = false;
  stopBtn.disabled = true;
  clearInterval(myCounter);
}

function counter() {
  i++; timer.value = i;
}

startBtn.addEventListener('click', startTimer);
stopBtn.addEventListener('click', stopTimer);
<button id="startBtn">Start</button>
<button id="stopBtn" disabled>Stop</button>
<h2><output id="timer">0</output></h2>

As an added measure, you can even hide the disabled button so only the active one is shown.

button:disabled {
  display: none;
}
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