Monday, November 21, 2005

Implementing a timer in JavaScript with setTimeout

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/implementing_a_timer_in_javascript_with_settimeout.htm]

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>
   

    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.

No comments:

Post a Comment