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

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.




5 Comments

speak up

Add your comment below, or trackback from your own site.

Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

*Required Fields