SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Time Master
By Scott Isaacs

Timers are an essential for creating live and interactive web pages. In this article, we present a framework for easily creating and manipulating timers to choreograph sequences of events and for creating simple animation loops.

What is web page animation? Web page animation includes anything that builds upon a set of timed events. When adding an animation, whether adding a clock, or moving an element around the screen, the underlying concept is almost always the same - a time period is specified, at which time a property on an object is updated. To demonstrate, below we create two variations of a clock. Both of these clocks are fundamentally the same. Every second, a property, whether it be the value of the text box or the status property on the window is updated.


By the conclusion of this article, you will learn how to take advantage of timers and to use our framework to create timed actions. For example, we created both clocks with a single function. By using our Timeline object, notice that the script consists of more comments than code!

  
  // Passing 0 to the new Timeline constructor causes the timeline to loop indefinitely
  
  // Create the Timeline for the clock in the textbox
  var clockDemo = new Timeline(0)  

  // Create the Timeline for the clock in the statusbar
  var statusDemo = new Timeline(0) 

  function updateTime(args) {
    // The args array contains all extra arguments 
    // as specified by the user
    // args[0] - The object being updated
    // args[1] - The property on the object to set the time to
 
    // See add function call in the doLoad() event
    args[0][args[1]] = new Date()
  }
  
  function doLoad() {
    // When the window is loaded, build the timeline sequence
   
    // 1000 - Call the function every second
    // updateTime - The function to call
    // All arguments after the function are optional and 
    // are passed to the function as the args array.
    // We chose to pass a reference to the object and 
    // the value to update
    clockDemo.add(1000,updateTime,document.forms.demo.clock, "value")
    statusDemo.add(1000,updateTime,window,"status")    
  
    // Start the clockDemo Timeline.  The statusDemo is not 
    // started at this point. Instead, the statusDemo is started 
    // when the button on the form is clicked.
    clockDemo.run()
  }
  window.onload = doLoad

Before we go into the details about the Timeline object, we explain the need for timers, how to use them, and difficulties timers have with passing object-valued arguments. An object valued argument are necessary when you want to animate or write really reusuable code. In our clock example above, the current time can be assigned to any property of any object just by passing a different object and property to the updateTime function.