| 1 |
'use strict'; |
| 2 |
module.exports = function (emitter, array, opts) { |
| 3 |
var index = 0; |
| 4 |
var running = true; |
| 5 |
var timer; |
| 6 |
|
| 7 |
opts = opts || {sync: true}; |
| 8 |
|
| 9 |
if (typeof opts === 'function') { |
| 10 |
opts = { |
| 11 |
sync: false, |
| 12 |
delay: 'immediate', |
| 13 |
done: opts |
| 14 |
}; |
| 15 |
} |
| 16 |
|
| 17 |
var sync = opts.sync; |
| 18 |
|
| 19 |
if (typeof sync !== 'boolean') { |
| 20 |
sync = !(opts.delay || opts.delay === 0 || opts.done); |
| 21 |
} |
| 22 |
|
| 23 |
function emit(args) { |
| 24 |
emitter.emit.apply(emitter, args); |
| 25 |
} |
| 26 |
|
| 27 |
function finish(err) { |
| 28 |
if (opts.done) { |
| 29 |
opts.done(err, index >= array.length); |
| 30 |
} |
| 31 |
} |
| 32 |
|
| 33 |
if (sync) { |
| 34 |
array.forEach(emit); |
| 35 |
index = array.length; |
| 36 |
finish(); |
| 37 |
return null; |
| 38 |
} |
| 39 |
|
| 40 |
var immediate = (!opts.delay && opts.delay !== 0) || opts.delay === 'immediate'; |
| 41 |
var delay = opts.delay; |
| 42 |
|
| 43 |
if (!immediate && typeof opts.delay !== 'number') { |
| 44 |
throw new TypeError('opts.delay must be a number'); |
| 45 |
} |
| 46 |
|
| 47 |
function next() { |
| 48 |
emit(array[index]); |
| 49 |
index++; |
| 50 |
scheduleNext(); |
| 51 |
} |
| 52 |
|
| 53 |
function scheduleNext() { |
| 54 |
if (index >= array.length) { |
| 55 |
stop(); |
| 56 |
} |
| 57 |
if (!running) { |
| 58 |
return; |
| 59 |
} |
| 60 |
timer = schedule(next); |
| 61 |
} |
| 62 |
|
| 63 |
function schedule(next) { |
| 64 |
if (immediate) { |
| 65 |
return setImmediate(next); |
| 66 |
} |
| 67 |
return setTimeout(next, delay); |
| 68 |
} |
| 69 |
|
| 70 |
function stop() { |
| 71 |
if (!running) { |
| 72 |
return; |
| 73 |
} |
| 74 |
running = false; |
| 75 |
if (immediate) { |
| 76 |
clearImmediate(timer); |
| 77 |
} else { |
| 78 |
clearTimeout(timer); |
| 79 |
} |
| 80 |
schedule(finish); |
| 81 |
} |
| 82 |
|
| 83 |
scheduleNext(); |
| 84 |
return stop; |
| 85 |
}; |