-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloop.js
39 lines (39 loc) · 980 Bytes
/
loop.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Asynchronous Loop
*
* @param {Number} iterations Number of times to run
* @param {Function} fn Function to execute in iteration.
* Must call loop.next() when finished.
* @param {Function} callback On loop finshed call back
*
* @example
* W.aloop(10,
* function (index, next, end) {
* log(index);
* next();
* },
* function () {
* log('finished');
* }
* );
*/
function loop ( iterations, fn, callback ) {
var index = 0;
var done = false;
var end = function() {
done = true;
callback();
};
var next = function() {
if ( done ) { return; }
if ( index < iterations ) {
index++;
fn( index-1, next, end );
} else {
done = true;
if ( callback ) { callback(); }
}
};
next();
return next;
}