Want timer to start on button click. Always starts on load. Why?

scripts

#1

I want it when the user clicks on the beginButton button, the timer will start to countdown. However, at the moment the timer always counts down on the load of the quiz. I am stuck to why this is.

Here is my HTML code:

<!DOCTYPE HTML>
<html>
<head>
<title> The London Guidebook Quiz</title>
<link rel="stylesheet" href="quizStyle.css">
<script src="quizScript.js"></script>  
</head>
<body>

<div id="frame001">
<h2> The London Guidebook: So, You Think You Know London? Quiz </h2>
<p id="userQuestion"> Question: <text id="number001"> 0 </text></p>
<p id="userScore"> Score: <text id="score001"> 0 </text> </p>
<div id="countDown"> </div>
<hr>

<div id="question001"> </div>
<br> <br>
<div> <img id="quizImage" img src="images/quizWelcome.jpg" height ="250px"
width="1115px"> </div>
<div> <img id="questionImages" </div>
<div id="option001"> </div>
<div id="option002"> </div>
<div id="option003"> </div>
<div id="option004"> </div>

<br>
<div id="disappear001"><button class="beginButton" onclick="begin001(), startTimer();"> Begin Quiz</button>
</div>

<br>
<div id ="result001">
<p id="resultMessage"> </p>
<img id="resultPicture">

<br><br>

<div id="userResult">
<p id="answer001"> </p>
<p id="answer002"> </p>
<p id="answer003"> </p>
<p id="answer004"> </p>
<p id="answer005"> </p>
<p id="answer006"> </p>
<p id="answer007"> </p>
<p id="answer008"> </p>
<p id="answer009"> </p>
<p id="answer010"> </p>

</div>
</div>

</body>

</html>

Here is my JavaScript code for the timer:

 var secondsDown = 60;
	 var timeIntervalUp = setInterval(function(){startTimer()}, 1000);

    function startTimer(){ 
            document.getElementById("countDown").innerHTML = "Time Remaining: " + secondsDown;
            secondsDown--;
			
             if (secondsDown == 0) {
                clearInterval(timeIntervalUp);
                endTimer();
                reload();
            }
        }
		
    function endTimer() {   
        document.getElementById("countDown").innerHTML = "Time ran out";
    }

    function reload(){
        window.location = "http://youtube.com";
  }

Thanks. :slight_smile:


#3

You've told your script to wait 1 second, and then start the timer.
Instead, try this:

	 var timeIntervalUp;

    function startTimer(){ 
         	 timeIntervalUp = setInterval(function(){countTimer()}, 1000);
   }
   function countTimer() {
            document.getElementById("countDown").innerHTML = "Time Remaining: " + secondsDown;
            secondsDown--;
			
             if (secondsDown == 0) {
                clearInterval(timeIntervalUp);
                endTimer();
                reload();
            }
        }

Because the actual setInterval command is now inside the function, it wont evaluate until the function is called by the button click.


#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.