Here is a script:
for(var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, 0);
};
Theoretically it should output just five "5" in console. But when we executing it in Chrome, Opera or Safari console, there are some strange numbers aside result. OS is macOS Sierra 10.12.1.
E.g.
Chrome 54.0.2840.98 (64-bit):
for(var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, 0);
};
2105
⑤ 5
Safari 10.0.1:
> for(var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, 0);
};
< 6
> for(var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, 0);
};
< 11
> for(var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, 0);
};
< 16
Opera 39.0:
for(var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, 0);
};
5
⑤ 5 VM73:2
for(var i = 0; i < 5; i++) {
setTimeout(function() { console.log(i); }, 0);
};
10
⑤ 5 VM74:2
You could try it yourself. What is interesting - same code included in HTML page works as it should. Depending on tab for which console is opened numbers are different. What is it? Guess it some kind of internal counter for cycles but not sure. Another thought - console shows what executing function return value. Perhaps it is. But for
does not return anything. At least it should not. Same code but without setTimeout
shows undefined
instead of strange numbers as it should works. Maybe somebody know about it a bit more than me and internet. Any thoughts are highly appreciated. Sorry for my English. Thank you!
Here's the minimal example:
for(var i = 0; i < 5; i++) setTimeout(function() {})
> 71 (or whatever)
Although statements don't have a value, the console tries to be "helpful" and outputs what the last evaluated expression returned - in this case it's setTimeout(...)
which returns the timeout ID - some arbitrary number.