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???