Created
March 13, 2015 15:17
-
-
Save lelandrichardson/c6fa767597e9663d9eca to your computer and use it in GitHub Desktop.
Asynchronous Serial iteration
This file contains hidden or 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 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; | |
} | |
}; | |
} |
This file contains hidden or 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
var data = [...]; | |
eachAsync(function (el, done){ | |
// ... do work | |
done(); // this could be called async | |
}, data); |
This file contains hidden or 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 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; | |
} | |
}; | |
} |
This file contains hidden or 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
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