So recently I was at a job interview and the following question appeared:
What will be the output of the following:
function print(i) {
console.log(i);
}
function call() {
for (var i=0;i<5;i++) {
window.setTimeout(function() {
print(i);
}, 0);
}
}
call();
The answer is that 5 will be printed 5 times to the log.
But why? What's going on here?
They told me it has to do with javascript's closure, but I don't really get what's happening in this scenario.
Thanks!
Aucun commentaire:
Enregistrer un commentaire