Creating Counter With Javascript

Apr 18 · 3 min read

In order to create a JavaScript counter, there are many ways to do it. In this post, we will learn two ways on how to do it.

1. Using setInterval

setInterval is a method in javascript to do some task repetitively in a certain time. We will directly create it in script tag inside HTML file, and console.log it into the browser. Here is how it is look like.

an image on how to create counter
an image on how to create counter
Create counter

There we declare a variable called counter, then we assigned value 0 to it. Then we create setInterval method to repetitively increment the counter value, and it will increase every 1000ms or every 1 second. You could also write it in a shorter syntax like this.

Create counter in more short ways

Those 2 ways will immediately fire once to browser is opened and will keep increase the counter as long as the browser is not refreshed.

2. Using a button

Another way to create a counter is to create a button in HTML, then assigned an onclick event to it. Here is how to do it.

Define a button

Here we create a button in HTML and give it an id btncounter.

Then we assigned it to a variable so we could give it an onclick listener event. The method inside onClick is relatively the same with the previous one but this time we don’t use setInterval anymore because the counter will only increase once the button is pressed.

Alternatively, you could also show the result into HTML instead of console log. Here is how its done.

Here we defined p tag and give it and id result.

Then instead of console log it we display the counter to HTML by using querySelector and give the counter result to it.

Thats it! That is how you could create a counter in javascript with several ways to do it. Hope to find this article help you, thanks for reading up to this point. Thank you!

Geek Culture

Proud to geek out. Follow to join our +500K monthly readers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store