Passing arguments to javascript’s setTimeout() method using closures

by klejnieks on August 21, 2008

Yesterday I ended up having to hack around FCKEditor a bit to “fine tune” it for a project im involved in. The problem was that the html text we needed from the editor was getting back to our app, I didnt touch the code at all except to add a console log (window.console.log()) and tada… it works now. Well it was aparent that the fckeditor was not getting to where i needed to get to fast enough.

Javascript has a method setTimeout, which if you google this, youll find a bunch of related topics on setTimeout, setInterval, and clearTimeout etc… So I went with a setTimeout to simply call the next function i needed 1 millisecond later.

...
setTimeout( doAlert(), 1 );
...
 
function doAlert()
{
	alert();
}

Great! that works… but wait, I need to pass it a few variables. No problem i figured i could just add them inline right?

...
var msg = "Hello World";
setTimeout( doAlert(msg), 1 );
...
 
function doAlert(msg)
{
	alert(msg);
}

Wrong. this wont work in IE which sadly enough we have to support, and my argument that everyone should use firefox or safari just doesnt ever seem to hold water in a big corporation.

So I googled around and came across a post on evolt showing how to add in parameters using closures. Now im not advocating the usage of closures, but I figure in this case it would have to do. So in the end my routine looked a little something like this

...
var msg = "Hello World";
var delay = function() { doAlert(msg); };
setTimeout(delay, 1);
...
 
function doAlert(msg)
{
	alert(msg);
}

this works like a champ on mac and windows in IE, FF, and safari.

{ 2 comments… read them below or add one }

1

vr113 09.24.08 at 4:55 am

That is the exact same issue I was facing - thx for this tip!

2

Thomas 12.15.08 at 1:11 pm

There’s an easier way to do this:


...
var msg = "Hello World";

setTimeout(doAlert, 1, [msg]);
...

function doAlert(msg)
{
alert(msg);
}

There’s no need for the delay function.

Furthermore, when passing a reference to a function as the first parameter to the setTimeout method, you’re supposed to pass the reference to the function, not a call to the function.

e.g.

// passing a call to the function is incorrect
var t = setTimeout(someFunction(), 1, argsArray);

vs.


// passing a *reference* to the function is correct
var t = setTimeout(someFunction, 1, argsArray);

Enjoy, Thomas

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>