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
is declared with keyword var
, it should be declared using let
Sep 20, 2020 at 10:48
i
, which will be 5 in this case.
Sep 20, 2020 at 11:08
// My code
should use variable i
. Although in this case the setInterval
solution is better, because it creates only one timer, while the setTimeout
solution creates a new timer and anonymous function for each iteration. In addition, the setInterval
solution allows you easily to interrupt the process whenever you need.
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);
setInterval
not work for you?1000
milliseconds. UsesetInterval
.