Using Javascript's setTimeout() with variable parameters

Posted in Javascript -

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:

var text = 'test';

The function is defined like so:

function example(text) {
    // do something with the text variable

The first example works, but it runs immediately rather than waiting for the time out because of the way the code is constructed:

setTimeout(example(text), 5000);

The second example doesn't work at all:

setTimeout("example("+text+")", 5000);

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:

setTimeout(function() { example(text) }, 5000);

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:

function example(param1, param2) {
    // do something here
setTimeout(example, 5000, 'msg1', 'msg2');

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.

Related posts: