Variable Issues Understanding Global Areas

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

Well, therefore, what I'm trying to do is add setTimeout in a loop and pass a variable value through it. Example:

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

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

I found a solution that looks like this:

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

I really don’t understand what it really is. It looks like it is returning the alert function back to the calling function, but I cannot interpret this.

, , , , -, , . , .

,

+5
3

, , , , - , setTimeout(), i.

1000 , for , , i 11.

, i , , x, setTimeout(), , .

for (i=0; i<11; i++) {
    setTimeout(function(x){
                 // CONTINUE HERE:
                 // x is a local variable to the function being executed
                 //    which references the current value of i

                 // A function is being returned to the setTimeout that
                 //    references the local x variable
                 return function(){ alert(x); };

               }(i) // START HERE:
                    // The "outer" function is executed immediately, passing the
                    //   current value of "i" as the argument.
     ,1000);
}

, , :

setTimeout( function(){ alert(x); }, 1000); //...where x === 0
setTimeout( function(){ alert(x); }, 1000); //...where x === 1
setTimeout( function(){ alert(x); }, 1000); //...where x === 2
setTimeout( function(){ alert(x); }, 1000); //...where x === 3
// etc.
+2

:

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

:

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

, i ( for) ( (i) ). :

function(){ alert(x); }

, , setTimeout() , , i , , , , .

+4

, , , :

setTimeout ( , eventlisteners), , , , .

, , , , .

, -- , , , (alert("1") not alert(i)).

, . , , , :

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

, , , , , , .

, , , , !

0

All Articles