|
||
| Inside Technique : Time Master : Timer Introduction Timers are an essential part of web-design and not using them for animation is one of the classic web-development mistakes. When adding an animation, a common error is to try and use a standard loop to create the animation. In the example below, we attempt to count and output in the text box values from 1 to 10. Even though we update the value at each loop iteration, you will only see the last value of the loop being displayed. This is because scripts must completely execute before the browser window is updated.
function demo2() {
for (var i=0; i < 10; i++)
document.forms.demo2.tb.value = i
}
To get the intended result, we need to change the loop to use a timer. By using a timer, you can insert a delay that between code execution giving the browser a chance to paint and update itself. Below we rewrite the above loop to correctly use a timer:
var count = 1
function rundemo2b() {
document.forms.demo2b.tb.value = count
if (count++<=10)
setTimeout("rundemo2b()",200)
else
count=1
}
The setTimeout function takes two arguments, a string containing a script to execute, and the number of milliseconds to wait before calling the function. To run the timer 10 times, we keep a global counter variable that we update on each call. Instead of using a global timer, we can pass the current count as an argument to the function. This eliminates the need for the global variable and creates more robust code. However, as we demonstrate next, passing variables with the setTimeout function has some inherent problems. Page 1:Time Master © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |