Java Reference
In-Depth Information
Quiz Ninja Project
We're now going add a timer to our quiz game with a “beat the clock” element to it. We'll do
this using the window object's setInterval() method to add a time limit to the game.
First of all, we'll add an element to the HTML for the timer. Add the following line to the
end of the <header> element inside the index.htm file:
<p id="timer"></p>
We also need to add this code inside the styles.css file to make the timer display in the center
of the header:
text-align: center;
Using its ID, add a reference to this element to the other DOM references in the scripts.js
var $timer = document.getElementById("timer");
We'll also add the following code to the start of the play() function:
// initialize timer and set up an interval that counts down
var time = 20;
var interval = window.setInterval( countDown , 1000 );
This sets a variable called time to 20 . It is used to measure, in seconds, how the game will
last. The next line updates the timer element with the initial time allowed for the game. The
last line sets up an interval that calls a function called countdown() every second (1,000
milliseconds). Let's write that function now. It can be placed anywhere inside the play()
function, but it is probably best placed near the end with all the other functions:
// this is called every second and decreases the time
function countDown() {
Search WWH ::

Custom Search