Skip to content

Instantly share code, notes, and snippets.

@yeisoncruz16
Last active April 27, 2021 20:45
Show Gist options
  • Save yeisoncruz16/ecf54a6dc878589858900ab4065a39d9 to your computer and use it in GitHub Desktop.
Save yeisoncruz16/ecf54a6dc878589858900ab4065a39d9 to your computer and use it in GitHub Desktop.
Simple asynchronous ForEach integration for Javascript without async/await or libraries.
function forEachOf(items, callback, finishCallback) {
if (items.length !== undefined && items.length > 0) {
this.key = this.key || 0;
if (this.key >= items.length){
this.key = 0;
finishCallback();
}else {
callback(items[this.key], this.key, () => {
this.key++;
forEachOf(items, callback, finishCallback);
});
}
} else {
finishCallback();
}
}
/**
* You can use it with Jquery or simple Array [0, 2 ,3]
* _this: mean the current the element
* key: the current element index
* callbackForNext: trigger the next item in the foreEach
**/
forEachOf($(selector), (_this, key, callbackForNext) => {
// Example with Timeout
setTimeout(()=>{
// Put Your asyn code Here Example
callbackForNext();
}, 2000); // Wait 2 Seconds and continue to next item
}, () => {
// This function is called when all the items were iterated
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment