setTimeout()This is a demonstration of how the JavaScript setTimeout(...) function can be used to perform some action on a regular basis. <SCRIPT LANGUAGE="JavaScript">
function DoSomethingUseful()
{
setTimeout("DoSomethingUseful()", 50);
}
</SCRIPT>
function DoSomethingUseful()
{
setTimeout("DoSomethingUseful()", 50);
}
</SCRIPT>
<HEAD>
<TITLE>setTimeout example</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var intPgColorIndex = 0;
var arrPgColor = new Array("#ffffff", "#999999", "#333333"); function SetPgColor()
{
var PgColor;
intPgColorIndex++;
if (intPgColorIndex >= arrPgColor.length)
{
intPgColorIndex = 0;
}
PgColor = arrPgColor[intPgColorIndex];
document.body.style.backgroundColor = PgColor;
setTimeout("SetPgColor()", 1000);
}
</SCRIPT>
</HEAD> <BODY ONLOAD="SetPgColor()"> </BODY>
</HTML>
Find the <BODY> tag near the bottom of the code listing ( line 23 ). The ONLOAD attribute causes the SetPgColor function to be called when the page first loads. The SetPgColor() function changes the background color of the page so you can see that it is doing something. The last line of SetPgColor() ( line 18 ) calls setTimeout(...) with a delay interval of 1000. setTimeout spawns a new thread that sits idle for 1000 milliseconds. Once the idle time is up, SetPgColor() is called again.