I have an array of data values and need to repeatedly call a javascript function with one after the other of those values as parameters. So I am doing a pretty straigthforward for-loop. My problem: I need to pause the execution of each step of the loop for a second, and I can't figure out how to do this. I already fiddled around with setTimeout(), but that only works for the whole function, not for one iteration of the for-loop. Is there a way to pause the execution of the for-loop before the next iteration?
Asked
Active
Viewed 869 times
2 Answers
0
Is there a way to pause the execution of the for-loop before the next iteration?
Not in a normal function, no. Instead of a for
loop, you handle the code for the first iteration, then schedule the next iteraton using setTimeout
, repeatedly until you're done. A search for "setTimeout
loop" will net you dozens of examples.
In an async
function, you can use for
if you give yourself a promise-enabled version of setTimeout
:
const delay = (ms, ...args) => new Promise(resolve => setTimeout(resolve, ms, ...args);
// ...
for (let i = whatever; i < whateverElse; i += something) {
// Do the thing, then
await delay(1000);
}
More about async
functions on MDN.

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875
0
edit: did you edit question or something, I read it as iterating and then random pause in middle of it, not every iteration 1second
const arr = [1, 2, 3, 4, 5, 6];
function* iterateArr () {
for (var i = 0; i < arr.length; i++) {
console.log(`Number ${i}`)
yield arr[i];
}
}
let iterate = iterateArr();
let c = 0;
while (c < 4) {
console.log(iterate.next());
c++;
}
console.log("OTHER CODE");
console.log(iterate.next());

WASD
- 310
- 1
- 9
-
Thank you very much, I'll dig into this and come back later. – inselfisch Dec 27 '18 at 16:06