Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing objects to functions called by setTimeout

Date format

Passing objects to functions called by setTimeout

by  philcha  Posted    (Edited  )
setTimeout's function / expression argument is treated as a string which is evaluated when the timeout expires. This has 2 consequences:
(a) If you pass an object directly to the target function you get an error because, for example, in
setTimeout("myFunction(myObject)", 500)
when the expression ("myFunction(myObject)" is evaluated the string value of myObject is "object".
(b) Getting the punctuation right is a pain, especially if part(s) of the argument(s) to the called function are quoted string(s). Then you wind up with mixtures of single quotes and double quotes, with variable names and + signs in between (e.g. double quotes for the strings which define the function / expression argument and single quotes for the strings you actually want to pass to the called function). Things get worse if you want to pass an HTML string containing double quotes.

The easiest way round problem (a) is to pass the name of the object variable as a string, e.g.
setTimeout("myFunction('myObject')", 500)
Note that this time myObject has single quotes.
But what if you want to use this function on more than 1 object? The easiest way I've found so far is give all my custom objects a property which contains the name of the object variable, preferably in the constructor, e.g.
myObject = new myObjectType("myObject");
creates a property myObject.varName = "myObject"
and then
setTimeout("myFunction(myObject.varName)", 500)
with no quotes round myObject.varName because it's a string variable.
You can use this approach to call methods of variable objects, e.g.
setTimeout(myObject.varName + ".myMethod(arguments)", 500)
but remember the dot before "myMethod"!

I often do the following to check that I've got the punctuation right:
* build the function / expression argument in a local variable.
* use alert to display the local variable. This allows me to see whether the call I'm generating is the call I want.
* pass setTimeout the variable as its function / expression argument.
* comment out the alert when it's working.
For example:
var X = "function_name(...........)";
alert(X);
setTimeout(X, interval);
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top