Javascript's setTimeout function executes code after a specified amount of time but can only handle constant parameters. This post looks at how to pass variable parameters to setTimeout.
What doesn't work
The following examples attempt to call the "example()" function which outputs the content from a variable defined as so, and which is passed as a parameter to the function in question:
The function is defined like so:
The first example works, but it runs immediately rather than waiting for the time out because of the way the code is constructed:
The second example doesn't work at all:
Firefox would show in the error console "Error: test is not defined" and Chrome "Uncaught ReferenceError: test is not defined". They attempt to access "test" as a variable which is the value of the variable.
What does work
I've shown what doesn't work so now here's how it does work:
By definining a function as the first parameter to setTimeout it is possible to pass a variable.
Another approach - the variable parameter list
As pointed out by a couple of commenters below, setTimeout has a variable parameter list so you can simply keep adding the extra parameters to the end of the function call like so, where 5000 is the timeout and "msg1" and "msg2" are the parameters:
BUT IT DOES NOT WORK IN INTERNET EXPLORER. At the time of the last update of this post (May 28th 2010) the most recent version of Internet Explorer is IE8 and it does not work in any version up to and including IE8. Depending which version of Javascript IE9 adheres to it may work in that version.
0 comments:
Post a Comment