All files ExponentialBackoff.ts

100% Statements 9/9
0% Branches 0/1
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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  1x                     1x         2x 2x 2x   2x       5x 5x 5x      
import { IBackoffStrategy } from "./BackoffStrategy";
import { wait } from "./Wait";
 
/**
 * Exponential backoff strategy that when supplied with a startMs value will
 * increment the timeout based on powers of the base. It uses the general
 * exponential function equation:
 *
 * ```
 * timeout = ab^x
 * ```
 */
export class ExponentialBackoff implements IBackoffStrategy {
    public timeout: number;
    public exp: number;
 
    constructor(
        readonly startMs: number,
        readonly base: number,
        readonly waitFn: (timeoutMs: number) => Promise<void> = wait,
    ) {
        this.exp = 0;
    }
 
    public async backoff(): Promise<void> {
        const timeout = this.startMs * Math.pow(this.base, this.exp);
        await this.waitFn(timeout);
        this.exp++;
    }
}