UNPKG

1.1 kBJavaScriptView Raw
1var RetryOperation = require('./retry_operation');
2
3exports.operation = function(options) {
4 var timeouts = exports.timeouts(options);
5 return new RetryOperation(timeouts);
6};
7
8exports.timeouts = function(options) {
9 if (options instanceof Array) {
10 return [].concat(options);
11 }
12
13 var opts = {
14 retries: 10,
15 factor: 2,
16 minTimeout: 1 * 1000,
17 maxTimeout: Infinity,
18 randomize: false
19 };
20 for (var key in options) {
21 opts[key] = options[key];
22 }
23
24 if (opts.minTimeout > opts.maxTimeout) {
25 throw new Error('minTimeout is greater than maxTimeout');
26 }
27
28 var timeouts = [];
29 for (var i = 0; i < opts.retries; i++) {
30 timeouts.push(this._createTimeout(i, opts));
31 }
32
33 // sort the array numerically ascending
34 timeouts.sort(function(a,b) {
35 return a - b;
36 });
37
38 return timeouts;
39};
40
41exports._createTimeout = function(attempt, opts) {
42 var random = (opts.randomize)
43 ? (Math.random() + 1)
44 : 1;
45
46 var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
47 timeout = Math.min(timeout, opts.maxTimeout);
48
49 return timeout;
50};
\No newline at end of file