The setInterval() method is a timing event that executes a method after specified time given in milliseconds, repeatedly. That is, if the timer is set to 3 seconds, the function is executed at every 3 seconds. The setInterval() is timing event defined in  HTML DOM Window object.

Syntax for setInterval()

var mytime = window.setInterval(“javascriptFunction”, “time in milliseconds”);

The setInterval() method can be cleared using clearInterval() method.This method stops the execution of setInterval() method.

Syntax for clearInterval()

window.clearInterval(mytime);

Advantage of using setInterval()

The setInterval() method is useful when a method has to be executed repeatedly.

Disadventage of using setInterval()

The setInterval() method associated with the setInterval() is called regularly when the time elapsed. But if there is another execution going on, the delay associated with calling the setInterval() function lasts longer than specified value and unwanted results may occur.

The example below shows a counter which displays incremented number every 1 second.

Example with setInterval() time based counter

 

›› go to examples ››