Javascript How to use Timer Loop


Javascript Timer Class

We can make JavaScript functions run at a specified time or at a specified interval.

the setTimeout method allows us to execute the function we want after the specified period, and the setInterval method allows us to repeat the function at the specified intervals.

the setTimeout method

It waits for the specified time in milliseconds, and then executes the specified function when that time expires. All methods described on this page belong to the window class and the window class is not written before the method names.

In the example below, when the button is clicked, the setTimeout method is executed and the print function is enabled after 2 seconds.

we can use the clearTimeout method if we want to prevent this method from running after the setTimeout method is started and the countdown begins.

in the clearTimeout method, it is necessary to specify the value returned by the setTimeout method that is wanted to be stopped. For this reason, when the setTimeout method is executed, it is synchronized to a variable. Using this variable in the clearTimeout method, the corresponding setTimeout method is stopped.

A setTimeout method used as above can be stopped without working as follows.

Example: there are two buttons on our page. The first one is to run the setTimeout method and run the print function after 3 seconds. The second button will stop the scheduled process with the clearTimeout method. This means that after pressing the first button, the operation can be cancelled by pressing the second button within 3 seconds.

Create the first button as follows::

The second button should be like this also:

setInterval() method

Its use is like the setTimeout method. If it does, it runs the specified function continuously with intervals until the specified time.

In the following example, BBB will be called twice per second and will include a period in box1.

Another example: let’s print the current time by updating it every second.

The clearInterval method is used to stop a scheduled function.

it is used in the same way as the clearTimeout method. The variable to which the setInterval method is to be stopped is used.

A setInterval method executed in the form of,

it can be stopped in its form.

Example: let’s prepare two buttons that start and stop counting back from 100.


google adwords vs google shopping