I have this but that doesn't seem to work
for (var i = 0; i < 5; i++) {
setTimeout(function() {
// My code
}, 1000);
}
It works one time but then it will not work
I have this but that doesn't seem to work
for (var i = 0; i < 5; i++) {
setTimeout(function() {
// My code
}, 1000);
}
It works one time but then it will not work
By using 1000
as your duration, it makes your code to look like it's only working for the first i
instance. What happens here is, for
loop executes quickly but each setTimeout
for each i
will almost be executed at the same time, but not exactly... there'll be split ms
between each i
.
let's say the loop executes within about 300ms
with each i
executed at 300ms
/ 5... this means each setTimeout
will be just 300/5 ms
behind the next one. So when this is executed, it will seem like the first i
is the one that shows the desired result and the others don't.
However, based on what I think you're trying to achieve, you should instead try to create a Timeout delay of about 1000ms
between each i
. So you should do it this way:
for (let i = 0; i < 5; i++) {
(function(i){
setTimeout(function() {
console.log(i);
}, i*1000);
})(i);
}
I think you should multiply your time by i. If you only put your time, all the iterations will execute at the same time after 1000 ms.
So the code will be:
for (var i = 0; i < 5; i++) {
setTimeout(function() {
// My code
}, 1000*i);
}
I think setInterval
is better for this case:
let i = 0;
const interval = setInterval(function() {
if(i == 4) clearInterval(interval);
// My code
console.log(i);
i++;
}, 1000);