Created
February 6, 2019 18:26
-
-
Save blakeyoder/96fe1ba03c965266552e40490b610a79 to your computer and use it in GitHub Desktop.
Stagger execution of a for loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const items = [1, 2, 3, 4, 5]; | |
let promise = Promise.resolve(); | |
for (let i = 0; i < items.length; i++) { | |
promise = promise.then(() => { | |
console.log(items[i]); | |
return new Promise((resolve) => { | |
setTimeout(resolve, 500); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of printing out the next iteration of the loop every 2 seconds, the above will add the callback function to the event queue to be called at a later time. This means that all items in the index will be printed out 2 (or so) seconds later. If we want to accomplish functionality that prints each iteration of the loop with a 2 second gap in between each print line, we can use promises to wait on the each execution of the loop.