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

180
Visualizações
Jquery Timer that starts and stops with same button

I can't for the life of my figure out how to get this to work bug free.

The button in the code below needs to do three things.

  1. Start a countdown when clicked (works)
  2. End the countdown automatically, and reset itself when it reaches 0(works)
  3. Reset itself prematurely if its clicked in the middle of a countdown(works, sort of)

Bug: when clicked repeatedly it starts multiple countdowns, and more or less breaks. It needs to either reset itself or start a countdown if clicked repeatedly. There should never be more than one countdown.

It works fines as long as people press the button, wait a second, and then press it again to stop it.
The bug I'm running into is if someone spam clicks it, it starts multiple countdowns and generally just breaks the button. I've tried a lot of different methods to fix it, and this is the closest I've gotten.

var i = 29;
let running=false;
$("#startButton").click(function () {     
    if(running==false){       
    var countdown = setInterval(function () {
        $("#startButton").text("Reset Timer"); 
        running=true;
        $("#stopWatch").html(i);
        i--;
        if (i <0)
    {
      $("#startButton").text("Start Timer");
      running=false;
      clearInterval(countdown);
      i = 29;
      $("#stopWatch").html(i); 
    }
     $("#startButton").click(function () {      
       $("#startButton").text("Start Timer");  
        running=false; 
      clearInterval(countdown);
      i = 29;
      $("#stopWatch").html(i+1);
    });
    }, 1000);
  }
    
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch">30</div>
<button  id="startButton">Start Timer</button>

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

0

Welcome to Stack Overflow @William!

I'm not sure what this means: Reset itself prematurely if its clicked in the middle of a countdown(works, sort of). But I managed to fix your bug on spamming button click and for item 3, i just do reset the countdown from initial state. See snippets below:

// Get attribute value from div `stopwatch`. This is for resetting from default value.
var initial = $('#stopWatch').attr("value");
// Assigned initial value to var i.
var i = initial;
$("#stopWatch").html(i); 
let running = false;

// Created a separate function to call from button click.
function run(timer = true) {
    if (timer) {
        running = true;
            $("#startButton").text("Reset Timer"); 
        $("#stopWatch").html(i);
        var countdown = setInterval(function () {
            i--;
            $("#stopWatch").html(i);
            if (i <= 0) {
                running = false;
                $("#startButton").text("Start Timer");
                clearInterval(countdown);
                i = initial;
                $("#stopWatch").html(i);
            }
            }, 1000);
    } else {
        running = false;
        clearInterval(countdown);
        i = 0;
        $("#startButton").text("Start Timer");
    }
}

$("#startButton").click(function () {  
        // Check if its not running and var i is not 0
    if(!running && i != 0) {   
                run();
    // Check if its running and var i is not 0 to ensure that if someone spam the button it just reset the countdown.
    } else if (running && i != 0) {
        // Will return the else{} on function run().
        run(false);
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stopWatch" value="30"></div>
<button  id="startButton">Start Timer</button>

Added some comments on the snippet. Feel free to ask if you have any questions.

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