I was going through learnyounode when I had to complete the juggling async challenge, and that is where I came across a similar simpler problem as below:
// try print numbers 0 - 9
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i)
})
}
the above snippet gives the output as:
10
10
10
10
10
10
10
10
10
10
which is not the intended result, however when I write it in the following way:
// try print numbers 0 - 9
var f = function(i) {
setTimeout(function() {
console.log(i)
})
}
for (var i = 0; i < 10; i++)f(i);
I get the desired output. So what is exactly happening when I am writing the setTimeout() portion inside that function?