using timer - setTimout

How to invoke a method after a specified time gap. or
How to execute a function repeatedly after a time interval in javascript?

Explanation

Object: Window
Method or Function: setTimeOut()
Syntax: setTimeout(name,milliseconds);
setTimeout method is used to execute an expression or function after a specified (set) time gap/interval. It takes two arguments,
- first the expression or function to be invoked, inside quotes
- second the time interval in milliseconds after which the execution will take place.
It's similar to setting a timer.

Example:


<script language=javascript>
function testtimeout(){
setTimeout("printer()",3000);
}
function printer(){
alert(" test set time out");
}
</script>
<form name=xcv>
<input type=button onClick="testtimeout()" value="test time out">
</form>

Result:


In the above example, in function testtimeout() we invoke printer() method using setTimeout and set the interval as 3 seconds. So the alert will popup after three seconds once testtimeout is executed.
Repeated Actions:
To make a repeated action after a specified time gap, we have to use setTimeout() inside the same function, which does the action.

Example:

This example will repeatedly add 1 to a number and show it after every 3 seconds (3000 milliseconds) .
Code:
<script language=javascript>
var x = 0; function testtimeout()
{
x = x+1; alert(" value of x is - "+x); setTimeout("testtimeout()",3000);
}
</script>
<form name=xcv>
<input type=button onClick="testtimeout()" value=close>
</form>

Result:




Ask Questions

Ask Question