Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable Global Scope understanding questions

my question is actually one of understanding - I have a working solution, I just don't understand how it works.

Okay, so - what I'm trying to do is adding a setTimeout in a loop, and passing a changing value through it. Example:

for (i=0;i<11;i++)
{
     setTimeout("alert(i)",1000);
}

If I understood correctly, this doesnt work because Javascript does not (like PHP) pass the value of i to the function, but passes a reference of i - which in turn is not static, but continues to change with the counter.

I found a solution, which goes like this:

for (i=0;i<11;i++)
{
    setTimeout(function(x){return function(){alert(x)};}(i),1000);
}

I don't really understand what this actually does. It looks like it passes a the "alert" function back to the calling function, but I can't make any sense of that.

I can work with this solution and also adapt it to other contexts, but I'd really like to understand all of my code, not just use stuff I found somewhere and be happy it works. And in addition, I'm looking for a slimmer version to achieve the same goal.

Thanks, Marco

like image 883
Marco P. Avatar asked Oct 18 '10 15:10

Marco P.


1 Answers

What this does:

function(x){return function(){alert(x)};}(i)

Is it takes a function:

function(x){ ...code... }

And executes it immediately, passing i (from the for loop) in as the only parameter (that's what the (i) on the end is for). This returns another function:

function(){ alert(x); }

It's that result that's being passed to setTimeout() as the function it calls when the timer's up, and it's not referencing the variable i in your loop that's changing, it's using the copy that was passed in when it created the new function.

like image 185
Nick Craver Avatar answered Oct 05 '22 07:10

Nick Craver