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.


Thursday, December 24, 2009 | Add Comment

New Comment

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