aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/heartbeater.ts
blob: dbc72da6a45cb26db56145eaf018a48a1be597f7 (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
import { intervalUtils } from '@0x/utils';
import * as _ from 'lodash';

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

    public constructor(performingFunctionAsync: HeartbeatableFunction, performImmediatelyOnStart: boolean) {
        this._performFunction = performingFunctionAsync;
        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._performFunction();
        }

        this._intervalId = intervalUtils.setAsyncExcludingInterval(this._performFunction, intervalTimeMs, () => {});
    }

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