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>

解决方案 »

  1.   

    Place the JavaScript setTimeout(...) function at the end of your function. By specifying the name of your function as the first parameter, setTimeout will call your function after a set amount of time has elapsed. You control how much time elapses with the second parameter. The time value is measured in milliseconds. A value of 1000 is one second. A value of 50 would be 1/20th of a second. To start things off, you must call your function once yourself. Then, just before your function exits, setTimeout spawns a new thread that sits and waits for the determined length of time. When that time elapses, the new thread calls the function referenced in the first parameter. The whole cycle continues forever, or until the page is unloaded from the browser. An important point about setTimeout is that it uses a secondary thread of execution. Without that, the primary thread would be busy waiting for the timeout, and nothing else would happen. Because of the secondary thread, the rest of your code continues to execute. Here's a more complete example. Listing 1<HTML> 
    <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.