I need to loop through a series of setTimeout functions, iteratively changing the function argument and the timeout value.
As discussed here, setTimeout performs (apparently) oddly in a for loop when printing values. You can use let
or define another function to resolve.
This works as expected: printing i every second
function doSetTimeout(i) {
setTimeout(function() { console.log(i); }, i * 1000);
}
for (var i = 1; i <= 5; ++i)
doSetTimeout(i);
This does not work as expected: printing i sequentially every second, five seconds, second, etc. Instead of 0, 1, 2, 3, 4, it logs 4, 0, 2, 1, 3 in the browser console.
times = [1,5,1,5];
function doSetTimeout(i) {
setTimeout(function() { console.log(i); }, times[i] * 1000);
}
for (var i = 0; i <= 4; ++i)
doSetTimeout(i);
I've experimented with using let
and an anonymous function and also not been successful.