How to create a counter in JavaScript – Multiple methods

In this tutorial, let’s look at how to create a counter in JavaScript. We’ll be creating 3 types of counters here: a click counter, an increment and decrement counter, and finally, an animated counter that counts down on its own.

Let’s get right into it then!

Click counter in JavaScript

Let’s start with the click counter. We’re going to create a counter that displays the number of times a button has been clicked by the user.

Our HTML is going to be very simple. We’ll have a simple H1 heading, a button with an id of ‘button’ to make things easier for us.

Finally, an empty div element with an id of ‘count’. We’re going to populate this div element with the click count. It’s going to get updated with the new value for every count.

    <h1>Click counter</h1>
    <button id="button">Click Me!</button>
    <div id="count"></div>

Now, let’s work on our script.js file. To start with, let’s retrieve the 2 HTML elements we want manipulated. We’re going to retrieve them by their unique ids.

let button = document.getElementById('button');
let count = document.getElementById('count');

Let’s also create a variable ‘c’ and assign it a starting value of 0. We’ll be incrementing this value every time the user clicks on our button.

let c = 0; 

Now, before we create an event listener for our button, let’s assign a starting string to our div element.

count.innerText = `The button was clicked ${c} times!`;

Run these lines of code, and you’ll get the following output:

counter in javascript

Clicking on our button does nothing yet though. Why? Well, we haven’t made it react to user clicks. The best way to do this is adding an event listener to our button element.

It requires 2 arguments: the event we’re listening to, which is a ‘click’ in our case, and what needs to be done when that event happens. We’re going to create an anonymous arrow function and increment the value of ‘c’ every time the click happens.

You can instead create a proper function, and just mention the name of said function as the 2nd argument. Both works.

Now, increment the value of ‘c’, and update the innerText of your ‘count’ div element.

button.addEventListener('click', () => {
    c++; 
    count.innerText = `The button was clicked ${c} times!`;
})

That’s it! Your output should look like this:

click counter in javascript

Look at where the arrow is pointing. That’s where your click count would get updated.

Increment and decrement counter in JavaScript

Now, let’s create an incremental and decremental counter. Basically, when we click on the ‘+’ button, we want our counter to go up by 1, and when we press on the ‘-‘ button, we want our counter to go down by 1.

It works similar to our click counter, but we need 2 buttons in this case. We’re giving them ids of ‘inc’ and ‘dec’.

We also need a place to display our count. We’re going to be using a H3 element of id ‘count’ now.

    <h1>Increment and decrement counter</h1>
    <h3 id="count"></h3>
    <button id="inc">+</button>
    <button id="dec">-</button>

Let’s retrieve all these 3 elements in our script file, and create a counter variable ‘c’ and assign it a starting value of 0.

let button = document.getElementById('button');
let inc = document.getElementById('inc');
let dec = document.getElementById('dec');
let c = 0; 

Let’s also assign our ‘count’ element a starting text, which is the starting value of the ‘c’ variable (0). We’re going to be updating this element every time the value of ‘c’ increments or decrements.

count.innerText = c;

Since we have 2 buttons, we need to create 2 event listeners, one for each button. Let’s start with and event listener for the increment button.

We’ll be incrementing the value of ‘c’ by 1, and updating the ‘count’ element.

inc.addEventListener('click', () => {
    c++; 
    count.innerText = c;
});

Similarly, let’s do the same for the decrement button.

dec.addEventListener('click', () => {
    c--; 
    count.innerText = c;
});

Now, if we look at the output, we’ll get:

javascript increment decrement counter

You don’t have to stop here. You can make the increment or decrement values anything you want. For example, you can make them increment or decrement by 5 for every click, or 0.5 instead of 1. It’s all up to you.

Create an animated counter in JavaScript using SetInterval

Finally, let’s create an animated counter using setInterval. We’re going to make our counter automatically count down from 10 and stop at 0. But we’re going to set this program up so that the count down only starts when the user presses the ‘Start Timer’ button.

We need to create a basic HTML page with a button of id ‘button’ and a H2 element of id ‘h2’.

    <h1>Countdown Timer</h1>
    <button id="button">Start Timer</button>
    <h2 id="h2"></h2>

Then, let’s retrieve those elements in our script file.

let button = document.getElementById('button');
let timer = document.getElementById('h2');

Let’s create a variable ‘secs’ and assign it a value of 10. You can make this value anything you want. I want my counter to count down from 10 secs, so I’m giving ‘secs’ a value of 10.

let secs = 10; 

Finally, let’s create our event listener. We’re going to add a click event listener to our ‘button’ element. On pressing this button, we want a setInterval to start.

Let’s assign this interval to a variable ‘interval’, so we can clear this interval when the time’s up.

Let’s set up the time up condition first. When the value ‘secs’ reaches 0, we want to update innerText of the ‘timer’ H2 element back to secs (0), so it doesn’t go to -1. Then, we need to clear the interval, and end everything with a return statement so our program comes out of the loop and stops execution.

When secs is not 0 (meaning, we still have counts to go), let’s assign the current value of ‘secs’ to the timer element’s innerText, and decrement the ‘secs’ value by 1, to create the countdown effect.

Finally, we as the 2nd argument of the setInterval, let’s give the milliseconds value as 1000 to indicate that we want this loop to repeat every 1000 milliseconds (every 1 second).

button.addEventListener('click',() => {
    let interval = setInterval(() => {
        if(secs == 0) {
            timer.innerText = secs;
            clearInterval(interval);
            return;
        }
        timer.innerText = secs;
        secs--;
    },1000);
});

That’s it! If you look at the output now, you’ll see:

animated counter javascript

There you go! These are the 3 ways of creating a counter in JavaScript.

Leave a Comment