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

130
Views
Mi reloj temporizador JS no se detiene cuando se hace clic dos veces en el botón de inicio

Tengo una lógica de cronómetro HTML simple donde puedo iniciar y detener el reloj con el clic del botón. Al hacer clic en el botón de start , se puede iniciar el temporizador (muestra la hora actual) y actualizar cada segundo. Uno puede detenerlo haciendo clic en el botón de stop . Pero si uno hace clic en el botón de start dos veces, no hay nada que pueda hacer para detener el temporizador. A continuación se muestra mi código:

 var hour = document.getElementById("hoursOut"); var minute = document.getElementById("minsOut"); var second = document.getElementById("secsOut"); var btnStart = document.getElementById("btnStart"); var btnStop = document.getElementById("btnStop"); var waitTimer; function displayTime() { var currentTime = new Date(); var currentHour = currentTime.getHours(); var currentMinute = currentTime.getMinutes(); var currentSeconds = currentTime.getSeconds(); hour.innerHTML = twoDigit(currentHour) + ":"; minute.innerHTML = twoDigit(currentMinute) + ":"; second.innerHTML = twoDigit(currentSeconds); } function twoDigit(digit) { if (digit < 10) { digit = "0" + digit; } return digit; } function startClock() { waitTimer = setInterval(displayTime, 1000); } function stopClock() { clearInterval(waitTimer); } btnStart.onclick = startClock; btnStop.onclick = stopClock;
 <h1>JavaScript Clock</h1> <div id="calendarBox"> <!-- OUTPUT TIME VALUES --> <p class="timeDisplay"> <span id="hoursOut">00:</span> <span id="minsOut">00:</span> <span id="secsOut">00</span> </p> <!-- BUTTON SET --> <input id="btnStart" type="button" value="START" /> <input id="btnStop" type="button" value="STOP" /> </div>

Revisé algunas respuestas en stackoverflow, pero la mayoría de las soluciones usan un for-loop de 0 a 1000 hasta que encuentra la identificación del intervalo y las detiene a todas usando el ciclo. Estoy seguro de que debería haber una solución elegante que esa.

 // some stackoverflow suggested answer for (var i = 1; i < 99999; i++) window.clearInterval(i);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Una posible solución es prevenir el problema antes de que suceda. Puede colocar una verificación en el temporizador de ejecución ( ¿Hay alguna forma de verificar si una var está usando setInterval ()? ).

En este caso, podría tener una variable de temporizador global var timer = false y agregar una verificación a la función de start . Luego, la función de stop establecerá la variable del temporizador de nuevo en falso.

 function startClock() { if(!timer){ timer = true waitTimer = setInterval(displayTime, 1000); } else return } function stopClock() { clearInterval(waitTimer); timer = false }
about 4 years ago · Juan Pablo Isaza Report

0

cuando hace doble clic, comienza un nuevo setInterval(). Así que ahora tiene dos intervalos establecidos en ejecución. El único problema es que no puede acceder al primero porque nombró al segundo con el mismo nombre. Compruebe si existe waitTimer y si lo detiene. ver código:

ACTUALIZACIÓN: en realidad ni siquiera necesita una declaración if. simplemente llame a stopClock () antes de configurar waitTimer - fragmento de código ajustado

 var hour = document.getElementById("hoursOut"); var minute = document.getElementById("minsOut"); var second = document.getElementById("secsOut"); var btnStart = document.getElementById("btnStart"); var btnStop = document.getElementById("btnStop"); var waitTimer; function displayTime() { var currentTime = new Date(); var currentHour = currentTime.getHours(); var currentMinute = currentTime.getMinutes(); var currentSeconds = currentTime.getSeconds(); hour.innerHTML = twoDigit(currentHour) + ":"; minute.innerHTML = twoDigit(currentMinute) + ":"; second.innerHTML = twoDigit(currentSeconds); } function twoDigit(digit) { if (digit < 10) { digit = "0" + digit; } return digit; } function startClock() { stopClock(); waitTimer = setInterval(displayTime, 1000); } function stopClock() { clearInterval(waitTimer); } btnStart.onclick = startClock; btnStop.onclick = stopClock;
 <h1>JavaScript Clock</h1> <div id="calendarBox"> <!-- OUTPUT TIME VALUES --> <p class="timeDisplay"> <span id="hoursOut">00:</span> <span id="minsOut">00:</span> <span id="secsOut">00</span> </p> <!-- BUTTON SET --> <input id="btnStart" type="button" value="START" /> <input id="btnStop" type="button" value="STOP" /> </div>

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!