Skip to content

Instantly share code, notes, and snippets.

@pthiers
Last active June 22, 2016 20:58
Show Gist options
  • Save pthiers/04f0ec6606d5e7af416c1621bf840418 to your computer and use it in GitHub Desktop.
Save pthiers/04f0ec6606d5e7af416c1621bf840418 to your computer and use it in GitHub Desktop.
async loop for array in js
function asyncLoop(array, func, callback) {
var iterations = array.length;
var index = 0;
var done = false;
var loop = {
next: function() {
if (done) {
return;
}
if (index < iterations) {
index++;
func(loop, array[index-1],array);
} else {
done = true;
callback();
}
},
iteration: function() {
return index - 1;
},
break: function() {
done = true;
callback();
}
};
loop.next();
return loop;
};
var test = [1,2,3,4,5,6,7,8];
asyncLoop(test, function(loop, element, arreglo){
console.log('elemento '+element);
loop.next();
},function(){
console.log('Fin');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment