|
||
| Inside Technique : Time Master : Passing Arguments When you specify the code for the timer, you are actually providing line of script to the language interpretor. Since the script is contained as an executable string, passing arguments can be quite tricky, especially when you want to pass object-valued arguments such as a text box or image. Below we will rewrite the simple counting timer to pass the current count directly to the function and to not use a global variable:
function rundemo2c(count) {
document.forms.demo2c.tb.value = count
if (count++<10)
setTimeout("rundemo2c("+count+")",200)
}
When passing the argument through the timer, it needs to be embedded into the script string. If the argument was a string value,
you would need to wrap the variable's value in quotes. Since you are building a string, what is actually be sent on the first call to the setTimeout function is the
literal value for the variable count: Passing of the literal values creates a difficult problem when trying to write generic code that reuses objects. Unfortunately, there is no direct way to pass objects through the timer as there is no literal representation of an object. For example, imagine you want to pass the text box into the timer for outputting the number. This would make the timer more generic and reusable. Since you cannot just simply insert the reference to the object into the function call, you can either store the object reference outside of the loop, or as we demonstrate next, create your own custom timer object. Passing objects are important especially when you want to write generic animation code. Our original clock demo is a great example as it was written to generically insert the clock into any property of any object. If you start animating elements, this becomes even more important. For example, if you want to write code that moves an element, it is better to pass the element rather than hard code the element into the code. This allows you to animate multiple elements with the same code. Netscape Navigator 4.0 did add a feature to solve this problem. In Navigator 4.0, you can specify additional arguments in the setTimeout function by appending them after the time argument. However, this only works in Navigator 4.0. Furthermore, Internet Explorer supports an optional third argument that can be used to specify an alternative scripting language for the script string. Due to this conflict with the third argument, we recommend you avoid using the extra argument solution (unless you are targeting Navigator 4.0 only), and instead us a solution similar to our Timeline object. Page 1:Time Master © 1997-2000 InsideDHTML.com, LLC. All rights reserved. |