aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/heartbeater.ts
blob: a5b42d87f5a9df216bc5e181ebf48970fc61a33d (plain) (blame)
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
import * as _ from 'lodash';

type HeartbeatableFunction = () => Promise<void>;
export class Heartbeater {
    private _intervalId?: number;
    private _hasPendingRequest: boolean;
    private readonly _performImmediatelyOnStart: boolean;
    private readonly _performFunction: HeartbeatableFunction;

    public constructor(performingFunctionAsync: HeartbeatableFunction, performImmediatelyOnStart: boolean) {
        this._performFunction = performingFunctionAsync;
        this._hasPendingRequest = false;
        this._performImmediatelyOnStart = performImmediatelyOnStart;
    }

    public start(intervalTimeMs: number): void {
        if (!_.isUndefined(this._intervalId)) {
            throw new Error('Heartbeat is running, please stop before restarting');
        }

        if (this._performImmediatelyOnStart) {
            // tslint:disable-next-line:no-floating-promises
            this._trackAndPerformAsync();
        }

        this._intervalId = window.setInterval(this._trackAndPerformAsync.bind(this), intervalTimeMs);
    }

    public stop(): void {
        if (this._intervalId) {
            window.clearInterval(this._intervalId);
        }
        this._intervalId = undefined;
        this._hasPendingRequest = false;
    }

    private async _trackAndPerformAsync(): Promise<void> {
        if (this._hasPendingRequest) {
            return;
        }

        this._hasPendingRequest = true;
        try {
            await this._performFunction();
        } finally {
            this._hasPendingRequest = false;
        }
    }
}