H I O X INDIA
Javascript Tutorial
Google
Web hscripts.com
 HOME  ||  Scripts  ||  Purchase  ||  Tutorials  ||  Images  ||  Tools  ||  Directories 
  :-)  Send Page   :-)   Feedback   :-)   Register   :-)   Links   :-)   Support   :-)   Bookmarks :-)  
 Forums   Hosting   Internet Stats   Easy Calculation   FUN Games 

Java-Script Tutorial
Introduction
Variables
Operators
Statements
Loops
Functions
Objects
Arrays
Browser Objects
Form DOM
Ask Your Doubts
Feedback





using timer - setTimout


Topic

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 Code:
<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:





        Javascript (JS) is one of the most used languages in the world. Some times spelled as Java Script. Hope you enjoy this tutorial. Do send your feedback or suggestions on this javascript or java script tutorial. This is a copyright content.

others

privacy policy     license     sitemap
© 2004-2005 HIOX INDIA - hioxindia.com

Other Links