helene
Version:
Real-time Web Apps for Node.js
63 lines • 2.01 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Heartbeat = void 0;
class Heartbeat {
_sendPing;
_onTimeout;
_seenPacket;
_heartbeatIntervalHandle;
_heartbeatTimeoutHandle;
static HEARTBEAT_INTERVAL = 10000;
constructor(options) {
this._sendPing = options.sendPing;
this._onTimeout = options.onTimeout;
this._seenPacket = false;
this._heartbeatIntervalHandle = null;
this._heartbeatTimeoutHandle = null;
}
stop() {
this._clearHeartbeatIntervalTimer();
this._clearHeartbeatTimeoutTimer();
}
start() {
this.stop();
this._startHeartbeatIntervalTimer();
}
_startHeartbeatIntervalTimer() {
this._heartbeatIntervalHandle = setInterval(() => this._heartbeatIntervalFired(), Heartbeat.HEARTBEAT_INTERVAL);
}
_startHeartbeatTimeoutTimer() {
this._heartbeatTimeoutHandle = setTimeout(() => this._heartbeatTimeoutFired(), Heartbeat.HEARTBEAT_INTERVAL);
}
_clearHeartbeatIntervalTimer() {
if (this._heartbeatIntervalHandle) {
clearInterval(this._heartbeatIntervalHandle);
this._heartbeatIntervalHandle = null;
}
}
_clearHeartbeatTimeoutTimer() {
if (this._heartbeatTimeoutHandle) {
clearTimeout(this._heartbeatTimeoutHandle);
this._heartbeatTimeoutHandle = null;
}
}
_heartbeatIntervalFired() {
if (!this._seenPacket && !this._heartbeatTimeoutHandle) {
this._sendPing();
this._startHeartbeatTimeoutTimer();
}
this._seenPacket = false;
}
_heartbeatTimeoutFired() {
this._heartbeatTimeoutHandle = null;
this._onTimeout();
}
messageReceived() {
this._seenPacket = true;
if (this._heartbeatTimeoutHandle) {
this._clearHeartbeatTimeoutTimer();
}
}
}
exports.Heartbeat = Heartbeat;
//# sourceMappingURL=heartbeat.js.map