Skip to content

Instantly share code, notes, and snippets.

@lelandrichardson
Created March 13, 2015 15:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lelandrichardson/c6fa767597e9663d9eca to your computer and use it in GitHub Desktop.
Save lelandrichardson/c6fa767597e9663d9eca to your computer and use it in GitHub Desktop.
Asynchronous Serial iteration
function eachAsync(iter, list, delay) {
var i = 0,
stopped = false,
fwhenDone;
delay = delay || 0;
function run() {
iter(list[i], done);
}
function hold() {
setTimeout(stopped ? hold : run, delay);
}
function done() {
i++;
if (i < list.length) {
setTimeout(stopped ? hold : run, delay);
} else if (fwhenDone) {
fwhenDone();
}
}
setTimeout(run, delay);
return {
stop: function () {
stopped = true;
},
start: function () {
stopped = false;
},
whenDone: function (f) {
fwhenDone = f;
}
};
}
var data = [...];
eachAsync(function (el, done){
// ... do work
done(); // this could be called async
}, data);
function whileAsync(iter, delay) {
var stopped = false;
delay = delay || 0;
function run() {
iter(next);
}
function next() {
setTimeout(stopped ? next : run, delay);
}
setTimeout(run, delay);
return {
stop: function () {
stopped = true;
},
start: function () {
stopped = false;
}
};
}
whileAsync(function (loop) {
// ... do work
if (condition) {
loop();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment