Skip to content

Instantly share code, notes, and snippets.

@adamauckland
Last active January 4, 2016 16:19
Show Gist options
  • Save adamauckland/8646145 to your computer and use it in GitHub Desktop.
Save adamauckland/8646145 to your computer and use it in GitHub Desktop.
/**
* An asynchronous loop implementation
*
* @param {array} inputArray
* @param {function} loopFunction: Function you want to call on each item.
* @example
*
var loopArray = [];
loopArray.push({ name: 'apple' });
loopArray.push({ name: 'ball' });
loopArray.push({ name: 'cat' });
loopArray.push({ name: 'duck' });
asyncLoop(loopArray, function(item, index, success) {
// do something with item
console.log(item);
console.log(index);
success();
}, function() {
// success, call the next function
console.log('Now call something else')
});
*
* @param {function} finishedFunction
*/
function asyncLoop(inputArray, loopFunction, finishedFunction, index) {
var sliceNextItem = inputArray.shift();
if(typeof index === 'undefined') {
index = 0;
} else {
index++;
}
if(typeof sliceNextItem !== 'undefined') {
loopFunction(sliceNextItem, index, function() {
asyncLoop(inputArray, loopFunction, finishedFunction, index);
});
} else {
finishedFunction();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment