JavaScript Tutorial





Español Français 中文 Deutsch Portuguese Japanese nederlands
   
 
Java-Script Tutorial
Introduction Introduction
Variables Variables
Operators Operators
Statements Statements
Loops Loops
Functions Functions
Objects Objects
Arrays Arrays
Cookies JS Cookies
Browser Objects Browser Objects
Form DOM Form DOM
Style Objects DOM Style Objects
Forums Ask Your Doubts
Scraps More about Javascript
Feedback Feedback
 




using timer - setTimout


Tutorials Javascript

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:





A Note
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.

Other Links

web hosting