WebSockets & Real-Time Communication

What considerations are important for implementing WebSocket heartbeat mechanisms?
class HeartbeatManager {
    constructor(ws, options = {}) {
        this.ws = ws;
        this.options = {
            pingInterval: 30000,
            pongTimeout: 5000,
            reconnectDelay: 3000,
            ...options
        };
        this.lastPong = Date.now();
    }

    start() {
        this.pingInterval = setInterval(() => {
            if (this.ws.readyState === WebSocket.OPEN) {
                this.ws.send('ping');
                this.waitForPong();
            }
        }, this.options.pingInterval);
    }

    waitForPong() {
        this.pongTimeout = setTimeout(() => {
            if (Date.now() - this.lastPong > this.options.pingInterval) {
                this.handleMissedPong();
            }
        }, this.options.pongTimeout);
    }

    handlePong() {
        this.lastPong = Date.now();
        clearTimeout(this.pongTimeout);
    }
}
Next Question (17/17)