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

218
Views
¿Cómo hago una función de cuenta regresiva en un botón en HTML5?

Estoy creando un juego tipo clicker en HTML5+Javascript y para la parte de hacer clic, hay un tiempo de espera... Lo probé yo mismo pero por alguna razón no funciona. HTML:

 function pursuit() { var btn = document.getElementById("pursuit"); setInterval(function(){ timeOnPursuit -= 1; }, 1000) while(timeOnPursuit > 0){ btn.value = "In Pursuit: " + timeOnPursuit; } }
 <div class="button"> <button id="pursuit" class="pursuit" onClick="pursuit()"> Go on a Pursuit </button> </div>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Algunas cosas a considerar aquí...

Primero, el código está generando un error en la consola del navegador. Nunca definió la variable timeOnPursuit , por lo que realmente no está controlando su alcance. Simplemente declare esa variable con un valor inicial (cualquier valor que desee) antes de intentar usarla:

 var timeOnPursuit = 10;

Aparte de eso, su bucle bloqueará el hilo. Debido a que la variable es inicialmente mayor que 0, y debido a que nada en ese ciclo modifica ese valor, se ejecutará para siempre y nunca permitirá que el intervalo tenga la oportunidad de modificar el valor.

Deshágase del bucle por completo y confíe en el intervalo en su lugar. Dentro del intervalo puede actualizar la interfaz de usuario. (Que, por cierto, probablemente debería ser innerText en lugar de value en este caso). Luego, dentro de ese intervalo, también puede verificar cuándo detener el intervalo, que es lo que sospecho que estaba tratando de hacer con el bucle.

Como beneficio adicional, es posible que también desee desactivar el botón para que el usuario no pueda volver a hacer clic en él, lo que crearía otro contador.

En general, tal vez algo como esto:

 function pursuit() { var btn = document.getElementById("pursuit"); // Start the "pursuit" var timeOnPursuit = 10; btn.innerText = "In Pursuit: " + timeOnPursuit; btn.disabled = true; // Repeat every second var interval = setInterval(function(){ // Update the "pursuit" timeOnPursuit -= 1; btn.innerText = "In Pursuit: " + timeOnPursuit; // Stop the interval at 0 if (timeOnPursuit <= 0) { clearInterval(interval); } }, 1000) }
 <div class="button"> <button id="pursuit" class="pursuit" onClick="pursuit()"> Go on a Pursuit </button> </div>

about 4 years ago · Juan Pablo Isaza Report

0

 function pursuit() { let timeOnPursuit = 10 // define time var btn = document.getElementById("pursuit"); const timer = setInterval(function() { console.log(timeOnPursuit) if (timeOnPursuit > 0) { btn.innerHTML = "In Pursuit: " + timeOnPursuit; timeOnPursuit -= 1; // reduce time } else { btn.innerHTML = "Pursuit"; clearInterval(timer) // stop the timer } }, 1000) }
 <div class="button"> <button id="pursuit" class="pursuit" onClick="pursuit()"> Go on a Pursuit </button> </div>

about 4 years ago · Juan Pablo Isaza Report

0

Iba a escribir mucho de lo que escribió David, así que ahora parece un poco redundante. En cambio, aquí hay un enfoque alternativo que usa setTimeout en lugar de setInterval .

 // Cache the element and add a click listener to it // (no need for inline JS) const btn = document.querySelector(".pursuit"); btn.addEventListener('click', pursuit, false); function pursuit() { // Initialise timeOnPursuit function loop(timeOnPursuit = 10) { // Display the button text, and disable the button btn.innerText = `In Pursuit: ${timeOnPursuit}`; btn.disabled = true; // If timeOnPursuit is greater than zero // call loop again with aa decremented timeOnPursuit if (timeOnPursuit > 0) { setTimeout(loop, 1000, --timeOnPursuit); } } // Call the loop function loop(); }
 <div class="button"> <button class="pursuit"> Go on a Pursuit </button> </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!