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

Inside Technique : Objects and Timers
By Scott Isaacs

Currently timers can only be passed primitive data types such as integers, strings, or booleans. However, often you need to pass an object such as an element to a timer. The most common work-around is to define a single global variable that stores a reference to a specific object.

An improvement over using a global variable that contains a single reference to an element is to create a global array that tracks state for each instance of the timer. In this example, we created three unique text boxes that will reuse the same function to run a clock. If you click the start clock button, a function is passed the text box for displaying the clock. Since the text box itself cannot be passed to the timer, it is stored in an array, and the index into the array is passed instead.

The code for used in this example is listed below. When looking at the code, notice how the text box object is cached in the clock array. By passing text boxe's index into the array to the timer, the timer function can easily retrieve the object.

    
  function runClock(index) {
    var clock = new Date
    // Retrieve the element from the clockArray
    clockArray[index].value = clock
    setTimeout("runClock("+index+")", 1000)
  }
   
  // Create an array to store the reference
  var clockArray = new Array()

  function start(src) {
    // Cache a reference to the element in the clockArray 
    if (src._index==null) {
      src._index = clockArray.length
      clockArray[src._index] = src
      // Run the timer passing an index into the clockArray
      setTimeout("runClock("+src._index+")", 1000)
    } else
    alert("This clock is already running.")
  }

This technique is very useful when combined with CSS Positioning. With CSS Positioning and scripting, you can animate elements in the 4.0 browsers. Animation in the 4.0 browsers require moving elements on a timer. With this technique you can reuse a single generic function to quickly and easily animate elements.

We use this technique to animate content from the sides of the screen in the sliding panels trade secret.IE4

Discuss and Rate this Article