+ 2
Infinite Loop Trap on JavaScript
This is my code for (let i = 0; i < 5; i++) { setTimeout(() => console.log(i), 1000); } Why does this print 5 five times instead of 0,1,2,3,4? How can we fix it? Please 🙏
2 Respuestas
+ 2
Normally with 'let' your code should print 0,1,2,3,4 (because 'let' is block-scoped inside the loop). If it printed 5 five times it might be due to an older JS environment (or you used 'var' instead of 'let' because 'var' is function-scoped). To be safe you can wrap i in a closure like this:
for (let i = 0; i < 5; i++) {
setTimeout((j => () => console.log(j))(i), 1000);
}
+ 1
It displays everything as it should. From 0 to 4.
This code displays from 1 to 5
for (let i = 1; i <= 5; i++) {
setTimeout(() => console.log(i), 1000);
}
5 to 5
var num = 5;
for (let i = 1; i <= 5; i++) {
setTimeout(() => console.log(num), 1000);
}
infinity loop with break
for (let i = 1; ; i++) {
if (i > 8) break;
console.log(i);
}