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

194
Visualizações
Timer will not fire "onclick". Fires on page load

I am trying to teach myself to code. I am coding a simple quiz. I would like my timer to fire on "start", and eventually, "next question". My timer starts once the page loads. Not sure why.

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

Have tried several different ways, including "addEventListener". Nothing seems to work.

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

0

If you take a look at a minimal example you'll see that this also runs as soon as the page is loaded. Here setInterval() is called when the script loads in the page. In turn the run() function is called every second.

var timerID = setInterval(run, 1000);

function run() {
    console.log("I'm running");
}

Think of the difference between var timer = run; and var timer = run(). The first assigns the function run to timer. The later executes run() and assigns the return value.

Here's your code with comments:

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

For a solution I've moved setInterval into the onclick handler and moved said handler assignment out of the myTimer function as you only want to setup your handlers once.

I've also renamed time to timerID to make it clear what it is.

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

I would suggest a couple of extra exercises to help you:

  1. Reset the timer so that you can click on the button to start the timer again
  2. Prevent the timer being started again (which would run multiple timers with different IDs) while a timer is running
about 4 years ago · Juan Pablo Isaza Relatório

0

The myTimer() function is never invoked. Even if you invoke it, it does not take any action. It's just repeating itself on click.

So, instead of:

function myTimer() {

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

Try adding an Event Listener:

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

Or use just the same code, but not inside a function, and its content to be a meaningful code that leads to the next answer:

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