+ 1
Why am I not achieving the sphere for this code and ending up getting 66666? Give the surface and deep reason why?
For (var i=1; i<=5; i++) { setTimeout (function(){ console.log ("i:" + i); }, i*1000); }
2 odpowiedzi
+ 1
It's because you used the var keyword. It will just look at the variable i and say, "hm, it looks like 6 to me", and outputs 6. But if you use the let keyword, there won't be a variable i, so it just says what it was told to say
Please use relevant tags xx byesies
+ 1
this is javascript, not java.
for() loop 5x initialise print i value with console.log(i) but each call of print function is executed after next i*1000 ms by setTimeout() . In first 1*1000 ms for() loop ends with value i=6. Then it first prints i and then repeatedly every i*1000ms.
try this modification
var a = 1;
for (var i=1; i<=5; i++) {
setTimeout (function(){
console.log ("a:" + a++);
}, i*1000);
console.log("i:" + i);
}
console.log("ends with i:" + i);
i:1
i:2
i:3
i:4
i:5
ends with i:6
a:1
a:2
a:3
a:4
a:5