Running the following code:
for (var i=0; i<3; i++) {
setTimeout( function() { console.log(i); } , 500 );
}
Outputs “3” three times. It’s outputting the final value of i as opposed to the value of i when the inner function is created.
If I want the output to be 1, 2, and 3, how would I write this code? How can I get it to use the value of i at the time the function is defined as opposed to its final value?
So, at
setTimeouttime (at the time we define the function forsetTimeout), we’re calling the anonymous function takingvalas a parameter. This creates a closure for each function call, storing the value ofvalwithin the scope of the function we just called. I used a self-invoking function, which creates an immediate closure.In the code you provided, the code creates a closure, but for the larger scope of the entirety of the code, so
iis local to the whole code, meaning that at run-time, the anonymous function will use the variableithat the rest of the code uses.