1. Using setInterval
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.
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.
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.