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

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

    public constructor(_performingFunctionAsync: HeartbeatableFunction) {
        this._performFunction = _performingFunctionAsync;
        this._hasPendingRequest = false;
    }

    public start(intervalTimeMs: number): void {
        if (!_.isUndefined(this._intervalId)) {
            throw new Error('Heartbeat is running, please stop before restarting');
        }
        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;
        }
    }
}