EN
JavaScript - how to make async loop class with next iteration confirmation?
1
points
In this article, we're going to have a look at how to write own loop asynchronous class that uses callback functions to execute next iteration in proper time or break loop.
Note: read this article to see how to write async loop that executes next iterations in groups - when resources are available.
// ONLINE-RUNNER:browser;
// AsyncLoop class
function AsyncLoop(index, count, onStarted, onIteration, onFinished) {
var READY = 0;
var EXECUTING = 1;
var WAITING = 2;
var state = READY;
function resume() {
if (state == EXECUTING) {
if (index < count) {
state = WAITING;
var proxy = function() {
state = EXECUTING;
onIteration(index++, resume, finish);
};
setTimeout(proxy, 0);
} else {
state = READY;
if (onFinished) {
onFinished(true);
}
}
}
}
function finish() {
if (state == EXECUTING) {
state = READY;
if (onFinished) {
onFinished(false);
}
}
}
this.run = function() {
if (state == READY) {
index = 0;
if (onIteration.length > 1) {
state = EXECUTING;
if (onStarted) {
onStarted();
}
resume();
} else {
if (onStarted) {
onStarted();
}
while(index < count) {
onIteration(index++);
}
if (onFinished) {
onFinished(false);
}
}
}
};
}
// Usage example:
function onStarted() {
console.log('loop started');
}
function onIteration(i, resume, finish) {
console.log('loop iteration');
setTimeout(resume, 500); // next iteration after 500ms
// resume() - continues loop
// finish() - breaks loop
}
function onFinished() {
console.log('loop finished');
}
var loop = new AsyncLoop(0, 5, onStarted, onIteration, onFinished);
loop.run();