+ 1
Why is the answer to this 333?
for(var i=0; i<3; i ) { setTimeout(function () { document.write(i); } ,200); } The code above was encountered in a challenge. Needless to say I failed it because I wasn't conversant this topic and I suspect it has something to do with asynchronous JavaScript which I'm yet to master. Please, why is the answer 333?
2 ответов
+ 1
the setTimeout method will run a function after some number of milliseconds, but only after the for loop has stopped executing, by the time the for loop has stopped executing, the value of i is 3. so each time the given function gets called, it will print out 3.
to solve this problem you have two choices either use the IIFE to capture i at each iteration like this:
for (var i=0; i<3; ++i) {
(function(i){
setTimeout(function () {
document.write(i);
},200);
})(i)
}
or simply use the let keyword instead of var:
for (let i=0; i<3; ++i) {
setTimeout(function () {
document.write(i);
} ,200);
}
+ 1
Thanks a lot, Mohamed. I would need to read up more on this topic