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

window.setInterval("functionname", time in milliseconds);

example

var intVal = setInterval(function(){alert('Timer Here')},4000);

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

<html>
<head>
</head>
<body>
	<button onclick="setInterval(function(){alert('Timer Here')},4000);">Call Timer</button>
</body>
</html>

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

clearInterval(intervalVariable)

Usage:

var timeVar = setInterval(function(){alert('Timer Here')},4000);
clearInterval(timeVar);

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

setTimeout("function name", time in milliseconds);

example

setTimeout(function(){alert('Just Once')},1000);

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

<html>
<head>
</head>
<body>
	<button onclick="setTimeout(function(){alert('Just Once')},1000);">Click Here</button>
</body>
</html>

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

clearTimeout(setTimeoutVal)

example

var timeVal = setTimeout(function(){alert('Just Once')
clearTimeout(timeVal);

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.