Last active
April 27, 2021 20:45
-
-
Save yeisoncruz16/ecf54a6dc878589858900ab4065a39d9 to your computer and use it in GitHub Desktop.
Simple asynchronous ForEach integration for Javascript without async/await or libraries.
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
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(); | |
} | |
} |
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
/** | |
* 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