Could someone explain this piece of code?
First, a variable called counter is defined and initialized to 0. This is will be responsible for the timer.
Further, the function increment_counter() is defined in which a variable counter_element is defined.
document.getElementById() is used to access the contents of a division or a paragraph in a html document identified by its id, which is “counter” in this case. “counter_element.innerHTML” is used to access that part of the HTML document and is being assigned to “counter” which has been initialized to 0 initially.
The next line is to increment the variable “counter”. So, every time the function increment_counter() is called, the value of counter will be incremented by 1 and hence be displayed on the webpage.
I hope this would help you understand the code.
I assume that you have some experience in web development, In this code we are trying to implement a counter which increments its value on certain interval.
In this function we have used setInterval() method which is used to call another function or evaluates an expression at set Interval, In our case we are calling increment_counter() function every 1000 ms or 1 sec.
Inside our function we have declared and initialized a variable named counter to zero, next we get the div element by its id counter and increment our variable counter by 1 and assign it to our div element of id counter.
Note that variable counter is the one we declare inside our script tag and div element counter is the one we have written inside our html tag.
Hope you understood, if you are having confusion in any part I have explained, just point it out!
Oh okay, thank you. It’s clear!