0
var messages = [
    "Hello, how are you??",
    "I'm good, thank you",
    "Yeah, it's been a long since we last spoke"
];

function test() {
    console.log(`it is inside the test function ${i}`);
}

for (var i = 0; i < messages.length; i++ ) {
    setTimeout(function() {
        console.log(`i am inside ${i}`);
    }, i * 2000);

    test();

}

Output of the above code is:

it is inside the test function 0 it is inside the test function 1 it is inside the test function 2 is it outside 3 i am inside 3

For the above code, why is the value of i inside the setTimeout function set to 3 in the first loop itself and not in case of the test function???

Pritam Bohra
  • 3,912
  • 8
  • 41
  • 72
  • This is actually a better duplicate https://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values?noredirect=1&lq=1 – Charlie Martin Jun 05 '17 at 21:22
  • `setTimeout` pushes the function to the end of the call stack. This means the loop will always have already finished before the first `setTimeout` function is executed. Since the loop is finished, the `i` value has already been incremented to 3 – Charlie Martin Jun 05 '17 at 21:24

0 Answers0