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

178
Views
Jquery Timer que se inicia y se detiene con el mismo botón

No puedo por mi vida averiguar cómo hacer que esto funcione sin errores.

El botón en el siguiente código necesita hacer tres cosas.

  1. Iniciar una cuenta regresiva al hacer clic (funciona)
  2. Finaliza la cuenta regresiva automáticamente y se restablece cuando llega a 0 (funciona)
  3. Se restablece prematuramente si se hace clic en medio de una cuenta regresiva (funciona, más o menos)

Error: cuando se hace clic repetidamente, comienza varias cuentas regresivas y más o menos pausas. Necesita reiniciarse o iniciar una cuenta regresiva si se hace clic repetidamente. Nunca debe haber más de una cuenta regresiva.

Funciona bien siempre que las personas presionen el botón, esperen un segundo y luego vuelvan a presionarlo para detenerlo.
El error con el que me estoy topando es que si alguien hace clic en él, comienza varias cuentas regresivas y, en general, solo rompe el botón. He probado muchos métodos diferentes para arreglarlo, y este es el más cercano que he tenido.

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

0

¡Bienvenido a Stack Overflow @William!

No estoy seguro de lo que esto significa: Reset itself prematurely if its clicked in the middle of a countdown(works, sort of) . Pero logré corregir su error al hacer clic en el botón de spam y para el elemento 3, solo restablecí la cuenta regresiva desde el estado inicial. Ver fragmentos a continuación:

 // 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>

Se agregaron algunos comentarios en el fragmento. No dude en preguntar si tiene alguna pregunta.

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!