-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsequence.js
69 lines (68 loc) · 1.59 KB
/
sequence.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
function Sequence(fn) {
var self = this;
var fns = [];
var done = function () {
fns.shift();
if (fns.length > 0) { triggerFn(fns[0]); }
return self;
};
this.then = function (fn) {
fns.push(fn);
return self;
};
this.delay = function (ms) {
self.then(function (done) {
setTimeout(done, ms);
});
return self;
};
this.start = function () {
triggerFn(fns[0]);
return self;
};
function triggerFn (fn) {
// it expects an done object
if (fn.length > 0) {
fn(done);
} else {
fn();
done();
}
}
if (typeof fn === 'function') {
this.then(fn);
}
return this;
}
/**
* A function sequencer with `delay` and `then` methods. Functions passed to `then` can have an optional argument `done` which can be used to trigger the function finishing
* @param {Function} fn optional first argument
* @return {[Sequencer]} object with `delay` and `then` methods.
* @example
* sequence(function (done) {
* console.log(0);
* done();
* })
* .then(function (done) {
* console.log(1);
* done();
* })
* .delay(1000)
* .then(function () {
* console.log(2);
* })
* .delay(1000)
* .then(function (done) {
* console.log(3);
* done();
* })
* .delay(1000)
* .then(function (done) {
* console.log(4);
* done();
* })
* .start();
*/
function sequence (fn) {
return new Sequence(fn);
}