Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Variable Scope [duplicate]

I'm having a problem with some JavaScript code.

Script

setTimeout(function() {
    for (var i = 0; i < 5; i++) {
        setTimeout(function() {
            console.log(i);
        }, i * 200);
    }
}, 200);

Outputs

5, 5, 5, 5, 5 instead of 1, 2, 3, 4, 5

I can kind of understand why this doesn't work, but I was wondering if someone could explain to me what's happening and why it's not working!

Also, how can this scope problem be overcome?

like image 296
Michael Waterfall Avatar asked Mar 13 '26 12:03

Michael Waterfall


1 Answers

The setTimeout callback functions are executed asynchronously, all the console.log calls you make refer to the same i variable, and at the time they are executed, the for loop has ended and i contains 4.

You could wrap your inner setTimeout call inside a function accepting a parameter in order to store a reference to all the i values that are being iterated, something like this:

setTimeout(function() {
    for (var i = 0; i < 5; i++) {
      (function (j) { // added a closure to store a reference to 'i' values
        setTimeout(function() {
            console.log(j);
        }, j * 200);
      })(i); // automatically call the function and pass the value
    }
}, 200);

Check my answer to the following question for more details:

  • Variables in Anonymous Functions — Can someone explain the following?
like image 71
Christian C. Salvadó Avatar answered Mar 15 '26 00:03

Christian C. Salvadó



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!