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);
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.