How to pass a parameter to setTimeOut javascript function?
You can always pass a parameter to setTimeOut
in an ugly way:
function ShowValue(a)
{
alert(a);
}
window.setTimeout("ShowValue(" + i + ");", 1000);
However, this is not going to work if you want to pass an object as a parameter. Here is where javascript closures become handy:
var i = 10;
window.setTimeout(function()
{
ShowValue(i);
}, 1000);
Where i
can be any kind of object. So, what are javascript closures?
Javascript closure is a mechanism for locking a local variable in the scope of a newly declared function.
i = 10;
window.setTimeout(function()
{
ShowValue(i);
}, 1000);
i = 20;
In the example above, ShowValue(i) would produce an alert message with a value of 20
. Why? Logically it should be 10
, since an assignment was done after function declaration. Actually, this is the right behavior. The declared function uses a pointer to the memory of a local variable. So, first i
gets a value of 10
, then it gets a value of 20
and only after that alert displays a value of i
using a memory pointer, which points to 20
.
You may say that it looks like a global variable of some kind. Actually, this is not a global variable. We can prove this using this example:
$(document).ready(function()
{
ShowPopup();
i = 30
});
function ShowPopup()
{
var i = 10;
window.setTimeout(function()
{
ShowValue(i);
}, 1000);
i = 20;
}
function ShowValue(a)
{
alert(a);
}
Above I am using jQuery ready function to execute ShowPopup
function. If i is a global variable then an alert should show 30
. But the alert still displays 20
. I hope after those little examples it becomes clear what is javascript closure.
And here is a classic implementation of javascript closures:
function ShowValue(j)
{
var i = j;
return function() { alert(i) };
}
$(document).ready(function()
{
window.setTimeout(ShowValue(10), 1000);
});
The Code above would be equivalent to window.setTimeOut('alert(10);',1000)
. You can even emit local variable i
, since j
can serve the same purpose. Here is a final snippet:
function ShowValue(j)
{
return function() { alert(j) };
}
$(document).ready(function()
{
window.setTimeout(ShowValue(10), 1000);
});