Creating Counter With Javascript

Tulusibrahim
Geek Culture
Published in
3 min readApr 18, 2021

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
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!

--

--

Tulusibrahim
Geek Culture

Frontend engineer, usually post some thought once in a while.