How to pass parameter to setTimeOut javascript function?

You can always pass 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 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 is javascript closures?

Javascript closure is a mechanism of locking local variable in a scope of newly declared function.

i = 10;

window.setTimeout(function()

{

    ShowValue(i);

}, 1000);

 

i = 20;

 

In example above, ShowValue(i) whould produce alert message with value 20. Why? Logically it should be 10, since assignment was done after function declaration. Actually, this a right behaivour. Declared function uses a pointer to a memory of local variable. So, first i gets value 10, then it gets value 20 and only after that alert displays 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 alert should show 30. But 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);
});

 

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);
});

Posted on Thursday, December 24, 2009 by | Add Comment

New Comment

Your Name:
Email (for internal use only):
Comment:
 
Code above:

Categories

Recent Tweets

Valid HTML5