Monday, November 15, 2010

Javascript: Passing local variable to setTimeout callback as parameter

In javascript, setTimeout is the only way to make asynchronous method call, however there is a limitation to use setTimeout method - the local variable can not be used as parameter in the callback method. The reason is once the callback is invoked by timer, the original method that calls setTimeout already returns and all the local variable are invalid.
A workaround for this issue is using javascript inner function, the outer functions local variable is visible to the inner function, even if the outer function returns.

Function function1( param )
{
var localVar = param + " is a local variable";
Function innerFunc()
{
alert( localVar );
}
window.setTimeout( innerFunc, 1000);
}

No comments:

Post a Comment