JavaScript Browsing With Closing: Help Me Understand

Running the following code:

for (var i=0; i<3; i++) { 
   setTimeout( function() { console.log(i); } , 500 ); 
}

Displays "3" three times. It outputs the final value ias opposed to the value iwhen creating the internal function.

If I want the result to be 1, 2, and 3, how would I write this code? How can I make it use a value iwhile defining a function, as opposed to its final value?

+5
source share
4 answers
for (var i=0; i<3; i++) {
   setTimeout( function(val) { return function() { console.log(val); } }(i), 500 );
}

, setTimeout ( setTimeout), , val . , val , . , closure.

, , , , i , , i, .

+6
function f(i){
  return function(){console.log(i);};
}

for (var i=0; i<3; i++) { 
   setTimeout( 
     f(i)
   , 500 ); 
}
+4

( , ) Function#bind. , ECMAScript Fifth Edition, :

for (var i=0; i<3; i++) {
    setTimeout(function(i) { console.log(i); }.bind(window, i), 500);
}

the window - , this ( this, ). , /, console.log, , :

for (var i=0; i<3; i++) {
    setTimeout(console.log.bind(console, i), 500);
}
+2

:

for (var i=0; i<3; i++) {
   (function(val){
       setTimeout(function() {
           console.log(val);
       },500)
   }(i));
}
+1

All Articles