Skip to content

Instantly share code, notes, and snippets.

@blakeyoder
Created February 6, 2019 18:26
Show Gist options
  • Save blakeyoder/96fe1ba03c965266552e40490b610a79 to your computer and use it in GitHub Desktop.
Save blakeyoder/96fe1ba03c965266552e40490b610a79 to your computer and use it in GitHub Desktop.
Stagger execution of a for loop
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);
});
});
}
@blakeyoder
Copy link
Author

const items = [1, 2, 3, 4, 5];

let promise = Promise.resolve();
for (let i = 0; i < items.length; i++) {
  setTimeout(() => console.log(items[i]), 2000);
}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment