Regarding Javascript program

Could someone explain this piece of code?

I assume you understand all html tags and only require explanation of the javascript code.

First, a variable called counter is defined and initialized to 0. This is will be responsible for the timer.

Next, a function start_timer() is defined. It uses the setInterval() function which is a predefined function in javascript used to execute a certain code again and again after a certain time interval. Here, in this case, the function increment_counter is being called, which is defined below, it at a regular interval of 1000ms or 1 second.

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.

1 Like

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.

  1. You can perform any javaScript function using attribute “onclick” on button element such as styling an element or changing the font size etc. In this case we have assigned a function “start_timer()” to the button "Start Timer"

  2. We have written two JavaScript functions in our script,
    i) start_timer()
    ii) increment_timer()

  3. start_timer() function-
    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.

  4. increment_counter() function-
    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!

1 Like

Oh okay, thank you. It’s clear!