Home > database >  Timer will not fire "onclick". Fires on page load
Timer will not fire "onclick". Fires on page load

Time:10-24

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.

  enter code here    

<!DOCTYPE html>`enter code here`
<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.

CodePudding user response:

The myTimer() function is never declared. Even if you declare 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 using just:

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

CodePudding user response:

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
  • Related