DEV Community

David Chedrick
David Chedrick

Posted on

Creating a simple timer and score keeper in JavaScript.

We are going to focus on creating a simple timer and score keeper using just HTML and JavaScript.

First we will start with creating our index.html with just basic HTML and our script tag that will connect our index.html and index.js:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Game</title>
</head>
<body>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Next, within the body we will add a div with an ID of "gameDiv". This div will hold the content of our game. Within "gameDiv" we will add two more divs that will hold our Time and Score. Both will contain a span that will hold our counts. These count numbers are what we will be manipulating with our JavaScript. As you see bellow, I named the spans with an ID of "timer" and "score". Remember,all of these ID names are what I chose to call them. You can name them whatever you want, but the name should be something that makes since to you and other people reading your code.

<body>
    <div id="gameDiv">
        <div>Time: <span id="timer">10</span></div>
        <div>Score: <span id="score">0</span></div>
    </div>
    <script src="index.js" type="text/javascript"></script>
</body>
Enter fullscreen mode Exit fullscreen mode

That is all we will put in our HTML file. Everything else will be done with JavaScript.
Start with creating a index.js that we already connected to our index.html.

First we will start with our global variables.
The .querySelector() makes it easier to write our code buy adding our selections into variables.

const gameDiv= document.querySelector('#gameDiv');
let timer = document.querySelector('#timer');
let score = document.querySelector('#score');
Enter fullscreen mode Exit fullscreen mode

startCountDown holds our setInterval() method which calls our function countDown, and we will add a 1000 millisecond delay:

let startCountDown = setInterval(countDown, 1000);
Enter fullscreen mode Exit fullscreen mode

Variables timeLeft and totalScore will hold the current values of our timer and score:

let timeLeft = 10;
let totalScore = 0;
Enter fullscreen mode Exit fullscreen mode

The next method we will utilize will be .addEventListener()
Once the DOM content is fully loaded it will call our first function renderGame:

document.addEventListener('DOMContentLoaded', renderGame())
Enter fullscreen mode Exit fullscreen mode

Now we are into our first function. Inside this function we still have access to our variables set in our global scope, but now we will add some variables that will now only have a function scope and will not be available outside of this function.
First we will create a new DIV using the .createElement() method:

function renderGame() {
    const gameCard = document.createElement('div');
Enter fullscreen mode Exit fullscreen mode

Next, we will create a button.
Now that we stored that created button into the variable click we can now type click to access our button.
Now we add in some text for our button and then we add on an event listener to our button. Our event listener will be triggered by a click from the mouse and will call on our function pointsClick:

    const click = document.createElement('button');
    click.textContent = 'CLICK FOR POINTS ';
    click.addEventListener('click', pointsClick);
Enter fullscreen mode Exit fullscreen mode

Lastly in this function we append our click variable to our gamecard. Then we append our gamecard to our gameDiv:

    gameCard.append(click);
    gameDiv.append(gameCard);
}
Enter fullscreen mode Exit fullscreen mode

The next function is pointsClick. It is called by the previous event listener we added in. Every time the button we created is clicked it triggers the event listener.
First in this function totalScore++ adds one to our score and score.innerText changes our score from a 0 to 1 on our webpage.

function pointsClick() {
    totalScore++
    score.innerText = totalScore
}
Enter fullscreen mode Exit fullscreen mode

Our countDown function was called at the top when we set our variable in global scope for our .setInterval() method.
First timeLeft-- will countdown our timer and timer.innerText will reflect that on our webpage.

function countDown(){
    timeLeft--;
    timer.innerText = timeLeft;
Enter fullscreen mode Exit fullscreen mode

Once timeLeft hits 0 we need an if statement to let the program know to go to our gameOver function.

    if(timeLeft === 0){
        gameOver();
    }
}
Enter fullscreen mode Exit fullscreen mode

Our last function is gameOver().
First we clearInterval so that our timer stops at 0.
Next, we have to grab that button we created earlier and tell the event listener to stop. Without taking off the event listener we would be able to continue to click for points even after the timer stopped.
Now we want to tell the player that the game is over and display the finial score.
So we create one more element, an h1 that will display our end game text on the screen.
Lastly we append the gameOver variable to our gameDiv.

function gameOver() {
    clearInterval(startCountDown);

    const button = document.querySelector('button')
    button.removeEventListener('click', pointsClick)

    const gameOver = document.createElement('h1');
    gameOver.innerHTML = 'GAME OVER!' + '<br>' + `Total Score: ${totalScore}`;

    gameDiv.append(gameOver);
}
Enter fullscreen mode Exit fullscreen mode

That is all we need to create a timer and score keeper. Try it out for yourself and then add this into a more complicated JavaScript game.

Click to see my example code.

Top comments (0)