socketioMEANseed/server/node_modules/backo2/index.js
server/node_modules/backo2/index.jsRaw
1
2/**
3 * Expose `Backoff`.
4 */
5
6module.exports = Backoff;
7
8/**
9 * Initialize backoff timer with `opts`.
10 *
11 * - `min` initial timeout in milliseconds [100]
12 * - `max` max timeout [10000]
13 * - `jitter` [0]
14 * - `factor` [2]
15 *
16 * @param {Object} opts
17 * @api public
18 */
19
20function Backoff(opts) {
21 opts = opts || {};
22 this.ms = opts.min || 100;
23 this.max = opts.max || 10000;
24 this.factor = opts.factor || 2;
25 this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
26 this.attempts = 0;
27}
28
29/**
30 * Return the backoff duration.
31 *
32 * @return {Number}
33 * @api public
34 */
35
36Backoff.prototype.duration = function(){
37 var ms = this.ms * Math.pow(this.factor, this.attempts++);
38 if (this.jitter) {
39 var rand = Math.random();
40 var deviation = Math.floor(rand * this.jitter * ms);
41 ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
42 }
43 return Math.min(ms, this.max) | 0;
44};
45
46/**
47 * Reset the number of attempts.
48 *
49 * @api public
50 */
51
52Backoff.prototype.reset = function(){
53 this.attempts = 0;
54};
55
56/**
57 * Set the minimum duration
58 *
59 * @api public
60 */
61
62Backoff.prototype.setMin = function(min){
63 this.ms = min;
64};
65
66/**
67 * Set the maximum duration
68 *
69 * @api public
70 */
71
72Backoff.prototype.setMax = function(max){
73 this.max = max;
74};
75
76/**
77 * Set the jitter
78 *
79 * @api public
80 */
81
82Backoff.prototype.setJitter = function(jitter){
83 this.jitter = jitter;
84};
85