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

406
Visualizações
Temporizador de cuenta regresiva jquery al reiniciar, se ejecuta más rápido que el tiempo establecido

Estoy tratando de hacer un temporizador de cuenta regresiva donde puedo cambiar el valor de la cuenta regresiva o descansar la cuenta regresiva, pero no puedo borrar el último temporizador, por lo que el valor del temporizador se agrega nuevamente a la velocidad si aumenta. Por favor, ayúdenme. Yo también. compartiendo el código.

 var sec = $("#timer_this").val(); $("#start").click(function() { var sec = $("#timer_this").val(); startTimer('start'); }); $("#reset").click(function() { $("#timer").html(0); var timex = 0; clearTimeout(timex); var timex = 0; startTimer('start'); }); $("#stop").click(function() { $("#timer").html($("#timer_this").val()); clearTimeout(timex); }); function startTimer() { timex = setInterval(function() { //document.getElementById('timer').innerHTML = sec + "sec left"; $("#timer").html(sec); sec--; if (sec == -1) { clearInterval(timex); time = null; alert("Time out!! :("); } }, 1000); } $("#stopbtn").click(function() { clearTimeout(timex); });
 <script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <input type="text" id="timer_this" value="1000"> <span id="timer"></span> <button id="start">start</button> <button id="stop">stop</button> <button id="pause">pause</button> <button id="reset">reset</button>

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

0

varias pequeñas cosas para tener una muestra de trabajo:

  • var timex ; debe declararse globalmente si desea establecer su valor en varias devoluciones de llamada
  • en la devolución de llamada de reinicio, haces var timex = 0; primer problema, recrea una función local variable timex pero debe hacerlo dos veces, eso no es válido
  • para la función de reinicio, puede simplemente hacerlo:
  1. crear una función de parada

  2. su devolución de llamada de reinicio se convirtió en

     $("#reset").click(function() { stopTimer(); startTimer(); }); 

 var sec = $("#timer_this").val(); var timex; $("#start").click(function() { var sec = $("#timer_this").val(); startTimer('start'); }); $("#reset").click(function() { stopTimer(); startTimer(); }); $("#stop").click(stopTimer); function stopTimer() { $("#timer").html($("#timer_this").val()); clearTimeout(timex); timex = undefined; } function startTimer() { if (!timex) { sec = $("#timer_this").val(); } timex = setInterval(function() { $("#timer").html(sec); sec--; if (sec == -1) { clearInterval(timex); time = null; alert("Time out!! :("); } }, 1000); } $("#pause").click(function() { clearTimeout(timex); });
 <script src="https://code.jquery.com/jquery-2.0.3.min.js" integrity="sha256-sTy1mJ4I/LAjFCCdEB4RAvPSmRCb3CU7YqodohyeOLo=" crossorigin="anonymous"></script> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script> <input type="text" id="timer_this" value="1000"> <span id="timer"></span> <button id="start">start</button> <button id="stop">stop</button> <button id="pause">pause</button> <button id="reset">reset</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

La variable timex se asignó en el ámbito de la función startTimer y se pierde una vez que la función regresa, por lo que no está disponible cuando más tarde llame a clearTimeout .

Al desarrollar su lógica, a menudo es útil crear funciones que describan las acciones que desea que sucedan y luego llamarlas desde los componentes de la interfaz de usuario. Esto ayuda a que el código sea más legible y reduce la repetición.

Por ejemplo, es más sencillo tener clearTimeout en un solo lugar y simplemente llamarlo desde cualquier método que necesite para detener el temporizador. También ayuda más tarde cuando la interfaz de usuario refleja el estado actual de la aplicación, ya que solo hay una forma de llegar a ese estado.

He aquí un ejemplo de este tipo de enfoque:

 let timerx, sec; $("#start").click(function() { // Toggle between start/stop sec ? stopTimer() : startTimer(); }); $("#pause").click(function() { // Toggle between pause/resume timerx ? pauseTimer() : resumeTimer(); }); function startTimer() { // Stop any existing timer stopTimer(); // Grab the new count sec = parseInt($("#timer_this").val()); // Start the timer resumeTimer(); $("#start").text("stop"); $("#pause").prop("disabled", false); } function resumeTimer() { // Start timer timerx = setInterval(() => { // Update time remaining $("#timer").text(--sec); if (sec === 0) { // Handle timeout stopTimer(); alert("Time out!! :("); } }, 1000); $("#timer").text(sec); $("#pause").text("pause"); } function stopTimer() { // Start timer and clear remainng time sec = 0; pauseTimer(); $("#timer").text(""); $("#start").text("start"); $("#pause").prop("disabled", true); } function pauseTimer() { // Just stop the timer timerx = clearInterval(timerx); $("#pause").text("resume"); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <input type="number" id="timer_this" value="1000"> <button id="start">start</button> <button id="pause" disabled>pause</button> <p id="timer"></p>

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