Timer

Javascript Timer

Javascript timer is an element of code that triggers after a certain period of time has elapsed. There are two types of Timers you can create in JavaScrit. One time Timers, that triggers just once after a certain period of time and the other one is long time firing timers , that continually triggers at set intervals.

setInterval() Method

The setInterval() Method is used to repeatedly call some function after a specified amount of time. It is commonly used to set a delay for functions that are executed repeatedly like animated pictures. The setInterval() Method returns a unique ID with which the timer can be canceled at a later time.

Syntax

example


When you click the above button, the setInterval method call the function and start execute. It will continuously alert with 4000 milliseconds interwel.

Stop setInterval() method

If you want to stop the execution of setInterval() method, call clearInterval() method and just pass the interval ID returned by the setInterval() method.

Syntax

Usage:

setTimeout() Method

Javascript setTimeout method

It is commonly used if you wish to have your function called once after the specified delay. That is, it will be run a specified number of milliseconds from when the setTimeout() method was called. The setTimeout() Method returns a unique ID with which the timer can be canceled at a later time.

Syntax

example


When you click the above button, it alert only one time.

How to Stop the setTimeout()

If You want to stop the execution of setTimeout() method, call clearTimeout() method and just pass the timeout ID returned by the setTimeout() method.

Syntax

example

Javascript Stop setTimeout

The setInterval() and setTimeout() methods are from HTML DOM Window object. The main difference is that setTimeout() triggers only once, and setInterval() keeps on triggering repeatedly unless you call it to stop.