Using built in intervalUtils instead of rolling own

This commit is contained in:
Steve Klebanoff
2018-11-09 15:28:08 -08:00
parent acb7e876b2
commit 5c1b1a1203

View File

@@ -1,15 +1,14 @@
import { intervalUtils } from '@0x/utils';
import * as _ from 'lodash';
type HeartbeatableFunction = () => Promise<void>;
export class Heartbeater {
private _intervalId?: number;
private _hasPendingRequest: boolean;
private _intervalId?: NodeJS.Timer;
private readonly _performImmediatelyOnStart: boolean;
private readonly _performFunction: HeartbeatableFunction;
public constructor(performingFunctionAsync: HeartbeatableFunction, performImmediatelyOnStart: boolean) {
this._performFunction = performingFunctionAsync;
this._hasPendingRequest = false;
this._performImmediatelyOnStart = performImmediatelyOnStart;
}
@@ -20,30 +19,16 @@ export class Heartbeater {
if (this._performImmediatelyOnStart) {
// tslint:disable-next-line:no-floating-promises
this._trackAndPerformAsync();
this._performFunction();
}
this._intervalId = window.setInterval(this._trackAndPerformAsync.bind(this), intervalTimeMs);
this._intervalId = intervalUtils.setAsyncExcludingInterval(this._performFunction, intervalTimeMs, () => {});
}
public stop(): void {
if (this._intervalId) {
window.clearInterval(this._intervalId);
intervalUtils.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;
}
}
}