forked from marmelab/gremlins.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bySpecies.js
71 lines (58 loc) · 2 KB
/
bySpecies.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
70
71
/**
* For each species, execute the gremlin 100 times, separated by a 10ms delay
*/
define(function(require) {
"use strict";
var executeInSeries = require('../utils/executeInSeries');
var configurable = require('../utils/configurable');
return function() {
/**
* @mixin
*/
var config = {
delay: 10, // delay in milliseconds between each attack
nb: 100 // number of attacks to execute (can be overridden in params)
};
var stopped;
var doneCallback;
/**
* @mixes config
*/
function bySpeciesStrategy(gremlins, params, done) {
var nb = params && params.nb ? params.nb : config.nb,
gremlins = gremlins.slice(0), // clone the array to avoid modifying the original
horde = this;
stopped = false;
doneCallback = done; // done can also be called by stop()
function executeNext(gremlin, i, callback) {
if (stopped) return;
if (i >= nb) return callback();
executeInSeries([gremlin], [], horde, function() {
setTimeout(function() {
executeNext(gremlin, ++i, callback);
}, config.delay);
});
}
function executeNextGremlin() {
if (stopped) return;
if (gremlins.length === 0) {
return callDone();
}
executeNext(gremlins.shift(), 0, executeNextGremlin);
}
executeNextGremlin();
}
bySpeciesStrategy.stop = function() {
stopped = true;
setTimeout(callDone, 4);
};
function callDone() {
if (typeof doneCallback === 'function') {
doneCallback();
}
doneCallback = null;
}
configurable(bySpeciesStrategy, config);
return bySpeciesStrategy;
};
});