1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | Object.defineProperty(exports, "__esModule", { value: true });
|
19 | exports.BackoffTimeout = void 0;
|
20 | const INITIAL_BACKOFF_MS = 1000;
|
21 | const BACKOFF_MULTIPLIER = 1.6;
|
22 | const MAX_BACKOFF_MS = 120000;
|
23 | const BACKOFF_JITTER = 0.2;
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | function uniformRandom(min, max) {
|
30 | return Math.random() * (max - min) + min;
|
31 | }
|
32 | class BackoffTimeout {
|
33 | constructor(callback, options) {
|
34 | this.callback = callback;
|
35 | this.initialDelay = INITIAL_BACKOFF_MS;
|
36 | this.multiplier = BACKOFF_MULTIPLIER;
|
37 | this.maxDelay = MAX_BACKOFF_MS;
|
38 | this.jitter = BACKOFF_JITTER;
|
39 | this.running = false;
|
40 | this.hasRef = true;
|
41 | if (options) {
|
42 | if (options.initialDelay) {
|
43 | this.initialDelay = options.initialDelay;
|
44 | }
|
45 | if (options.multiplier) {
|
46 | this.multiplier = options.multiplier;
|
47 | }
|
48 | if (options.jitter) {
|
49 | this.jitter = options.jitter;
|
50 | }
|
51 | if (options.maxDelay) {
|
52 | this.maxDelay = options.maxDelay;
|
53 | }
|
54 | }
|
55 | this.nextDelay = this.initialDelay;
|
56 | this.timerId = setTimeout(() => { }, 0);
|
57 | clearTimeout(this.timerId);
|
58 | }
|
59 | |
60 |
|
61 |
|
62 | runOnce() {
|
63 | var _a, _b;
|
64 | this.running = true;
|
65 | this.timerId = setTimeout(() => {
|
66 | this.callback();
|
67 | this.running = false;
|
68 | }, this.nextDelay);
|
69 | if (!this.hasRef) {
|
70 | (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
|
71 | }
|
72 | const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay);
|
73 | const jitterMagnitude = nextBackoff * this.jitter;
|
74 | this.nextDelay =
|
75 | nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude);
|
76 | }
|
77 | |
78 |
|
79 |
|
80 |
|
81 | stop() {
|
82 | clearTimeout(this.timerId);
|
83 | this.running = false;
|
84 | }
|
85 | |
86 |
|
87 |
|
88 | reset() {
|
89 | this.nextDelay = this.initialDelay;
|
90 | }
|
91 | isRunning() {
|
92 | return this.running;
|
93 | }
|
94 | ref() {
|
95 | var _a, _b;
|
96 | this.hasRef = true;
|
97 | (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a);
|
98 | }
|
99 | unref() {
|
100 | var _a, _b;
|
101 | this.hasRef = false;
|
102 | (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a);
|
103 | }
|
104 | }
|
105 | exports.BackoffTimeout = BackoffTimeout;
|
106 |
|
\ | No newline at end of file |