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

168
Views
La velocidad del contador aumenta cuando se vuelve a hacer clic en el botón de inicio

Cuando se hace clic en el botón de inicio una vez, todo funciona perfectamente bien. Sin embargo, cuando se hace clic en el botón de inicio varias veces (por accidente, por ejemplo), la velocidad del contador aumenta y el botón de parada parece no funcionar más.

¿Por qué está pasando esto? ¿Y qué puedo hacer para evitar que el botón de inicio (si se hace clic accidentalmente) aumente la velocidad del temporizador cuando ya se está ejecutando?

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

0

Bienvenido a StackOverflow.

Dentro de su pregunta, no está claro si desea que el temporizador se reinicie si el usuario vuelve a hacer clic en el botón de inicio; sin embargo, con mi respuesta, llegué a la conclusión de que no lo hizo.

Aquí hay una versión modificada de startTimer() que utiliza una cláusula de protección para verificar si ya existe un intervalo (y si es así, no comience de nuevo)

 function startTimer() { // Guard clause! If the counter exists, exit the function! if(myCounter) { return } myCounter = setInterval(counter, 200); }

También se necesita una pequeña actualización de la función de parada para set myCounter en null después de que se detenga el contador:

 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; }

Espero que esto haya ayudado :)

about 4 years ago · Juan Pablo Isaza Report

0

Agregué una variable que puede ayudarte a detectar si el contador ya está presionado o no, con la condición de esa variable, puedes tener lo que quieras, edité tu código.

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

0

Simplemente puede deshabilitar el botón de inicio una vez que se hace clic y volver a habilitarlo cuando se hace clic en el botón de detener.

 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>

Como medida adicional, puedes incluso ocultar el botón deshabilitado para que solo se muestre el activo.

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