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.
xxxxxxxxxx
1
// AsyncLoop class
2
3
function AsyncLoop(index, count, onStarted, onIteration, onFinished) {
4
5
var READY = 0;
6
var EXECUTING = 1;
7
var WAITING = 2;
8
9
var state = READY;
10
11
function resume() {
12
if (state == EXECUTING) {
13
if (index < count) {
14
state = WAITING;
15
var proxy = function() {
16
state = EXECUTING;
17
onIteration(index++, resume, finish);
18
};
19
setTimeout(proxy, 0);
20
} else {
21
state = READY;
22
if (onFinished) {
23
onFinished(true);
24
}
25
}
26
}
27
}
28
29
function finish() {
30
if (state == EXECUTING) {
31
state = READY;
32
if (onFinished) {
33
onFinished(false);
34
}
35
}
36
}
37
38
this.run = function() {
39
if (state == READY) {
40
index = 0;
41
if (onIteration.length > 1) {
42
state = EXECUTING;
43
if (onStarted) {
44
onStarted();
45
}
46
resume();
47
} else {
48
if (onStarted) {
49
onStarted();
50
}
51
while(index < count) {
52
onIteration(index++);
53
}
54
if (onFinished) {
55
onFinished(false);
56
}
57
}
58
}
59
};
60
}
61
62
// Usage example:
63
64
function onStarted() {
65
console.log('loop started');
66
}
67
68
function onIteration(i, resume, finish) {
69
console.log('loop iteration');
70
setTimeout(resume, 500); // next iteration after 500ms
71
72
// resume() - continues loop
73
// finish() - breaks loop
74
}
75
76
function onFinished() {
77
console.log('loop finished');
78
}
79
80
var loop = new AsyncLoop(0, 5, onStarted, onIteration, onFinished);
81
loop.run();