Friday 10 June 2011

Javascript: Pass parameter into setTimeout


Sometimes passing a parameter into a function, specified within a setTimeout() function isn't so straight forward. Different browser garbage collectors operate differently, and your function sometimes won't be executed at all.

Here is a method that works in all browsers. You need to specify the function within an anonymous function, and set the parameter to null.

Code Sample
var foo = "Hello World";
setTimeout(function () { helloWorld(foo); foo = null }, 3000);
 
function helloWorld(foo)
{
    alert(foo);
}

No comments: