Great Use For Javascript Closures
Posted on June 24th, 2009 in Everyday Tips, PHP, Web Development | No Comments »
setTimeout() with a paramter
If you need to use the setTimeout() function to call a javascript function that accepts a parameter you might be tempted to use syntax like
setTimeout('functionName()', 1500, param1, param2, etc);
And you would probably have success until you went to test your site in Internet Explorer. Firefox seems to be able to handle the extra parameters on the end of the setTimeout() call but IE simply sends undefined variables to the function you are calling and your script dies.
Here is the solution – use closures! They are a little tricky to understand if you are new to the idea but, in a nutshell, you are assign a function to a variable. Normally you assign numbers, or strings to variables – well you can assign functions to variables too. Here’s how:
setTimeout(function() { delayedFunctionName(param1); }, 1500);
This causes the function delayedFunctionName(p1) to be called with a 1.5 second delay AND the p1 parameter actually gets a value!
