Sometimes, we want to create pause or delay in a JavaScript for loop.
In this article, we’ll look at how to create pause or delay in a JavaScript for loop.
How to create pause or delay in a JavaScript for loop?
To create pause or delay in a JavaScript for loop, we should use await with a for-of loop.
For instance, we write:
const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms))
const loop = async () => {
for (const a of [1, 2, 3]) {
console.log(a)
await wait(2000)
}
}
loop()
to define the wait function that returns a promise that calls setTimeout with resolve to resolve the promise in ms milliseconds.
Then we define the loop function that runs a for-of loop to loop through an array.
In the loop body, we call wait with await to pause the loop for 2000 milliseconds before continuing to the next iteration.
As a result, we see that the numbers are logged after a 2 seconds delay between each iteration.
Conclusion
To create pause or delay in a JavaScript for loop, we should use await with a for-of loop.