The World’s Leading Microsoft .NET Magazine
   
 
timstall

Donate Today!

Search Box

 

Calendar

««Jul 2009»»
SMTWTFS
    12
3
4
567891011
12131415161718
19202122232425
262728293031

My RSS Feeds








Mailing List

Most Popular Tags

                                                           

Implementing a timer in JavaScript with setTimeout

posted Tuesday, 22 November 2005

Sometimes you want something cycling in the background to give your page an active feel, like images or text labels updating every 4 seconds. You can do that with the JavaScript setTimeout function. The script below keeps a running clock:

<html>
  <head>
    <script language=javascript>
    <!--
    function SetTime()
    {
      var s = new Date();
      document.getElementById("Span1").innerText = s;
    }
    function UpdateCycle() {
        SetTime();
      setTimeout("UpdateCycle()",500);
    }
    //-->
    </script>
  </head>
  <body MS_POSITIONING="FlowLayout" onload="UpdateCycle()">
    <form id="Form1" method="post" runat="server">
      This is a timer test.
      <span id="Span1"></span>
    </form>
  </body>
</
html
>

This method takes a method to call, and the time (in milliseconds) to wait. The pattern is simple:

  1. Have the body onload event call the looping function, like UpdateCycle(). This function manages the cycling.
  2. Have the looping function call whatever action you want, and the setTimeOut method.
  3. Implement the action method (in this case SetTime) to do whatever action you need.

You could even make a global variable, increment it in each UpdateCycle, and therefore keep a global counter of how many cycle have passed. You could also have the body onload call an initialization method instead, that method would do start-up initialization, and then call the UpdateCycle method.

This is a simple JavaScript method to use, but it can have a big return to help certain pages feel more lively.

links: digg this    technorati    




1. Enlightened left...
Friday, 10 October 2008 12:45 am

This is more practical:

<body onload="setInterval(SetTime(),500)">

Then remove your UpdateCycle() function.