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

190
Views
El temporizador no disparará "onclick". Se dispara al cargar la página

Estoy tratando de enseñarme a mí mismo a codificar. Estoy codificando un cuestionario simple. Me gustaría que mi temporizador se active en "inicio" y, finalmente, "próxima pregunta". Mi temporizador comienza una vez que se carga la página. No estoy seguro de por qué.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <button id="b1">Click Me!</button> <p id="demo"></p> <script> var sec = 5; var time = setInterval(myTimer, 1000); function myTimer() { document.getElementById("b1").onclick = function() { myTimer() }; document.getElementById('demo').innerHTML = sec + "sec."; sec--; if (sec <= -1) { clearInterval(time); // alert("Time out!! :("); document.getElementById("demo").innerHTML="Time's up!"; } }

He intentado varias formas diferentes, incluido "addEventListener". Nada parece funcionar.

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

0

Si observa un ejemplo mínimo, verá que esto también se ejecuta tan pronto como se carga la página. Aquí se llama setInterval() cuando el script se carga en la página. A su vez, la función run() se llama cada segundo.

 var timerID = setInterval(run, 1000); function run() { console.log("I'm running"); }

Piense en la diferencia entre var timer = run; y var timer = run() . El primero asigna la función run al timer . El último ejecuta run() y asigna el valor de retorno.

Aquí está su código con comentarios:

 var sec = 5; // start interval timer and assign the return value "intervalID" to time var time = setInterval(myTimer, 1000); // to be called every second function myTimer() { // assign an onclick handler to "b1" EVERY SECOND! document.getElementById("b1").onclick = function() { myTimer() }; // update the demo DOM element with sec document.getElementById('demo').innerHTML = sec + "sec."; sec--; if (sec <= -1) { clearInterval(time); // alert("Time out!! :("); document.getElementById("demo").innerHTML="Time's up!"; } }

Para una solución, moví setInterval al controlador onclick y moví dicha asignación de controlador fuera de la función myTimer ya que solo desea configurar sus controladores una vez.

También cambié el nombre de time a timerID para que quede claro de qué se trata.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> </head> <body> <button id="b1">Click Me!</button> <p id="demo"></p> <script> var sec = 5; var timerID; document.getElementById("b1").onclick = function() { timerID = setInterval(myTimer, 1000); }; function myTimer() { document.getElementById('demo').innerHTML = sec + "sec."; sec--; if (sec <= -1) { clearInterval(timerID); // alert("Time out!! :("); document.getElementById("demo").innerHTML="Time's up!"; } } </script> </body> </html>

Te sugiero un par de ejercicios adicionales para ayudarte:

  1. Restablezca el temporizador para que pueda hacer clic en el botón para iniciar el temporizador nuevamente
  2. Evite que el temporizador se inicie nuevamente (lo que ejecutaría varios temporizadores con diferentes ID) mientras se ejecuta un temporizador
about 4 years ago · Juan Pablo Isaza Report

0

La función myTimer() nunca se invoca. Incluso si lo invocas, no realiza ninguna acción. Simplemente se repite al hacer clic.

Entonces, en lugar de:

 function myTimer() { document.getElementById("b1").onclick = function() { myTimer() };

Intente agregar un detector de eventos :

 document.getElementById("b1").addEventListener('click', function() { // inside here you put the code for going into next question })

O use el mismo código, pero no dentro de una función, y su contenido sea un código significativo que lleve a la siguiente respuesta:

 document.getElementById("b1").onclick = function() { // code to proceed into next question }
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!