From 52c60d06276cf700883965b0c3c55509565ddd92 Mon Sep 17 00:00:00 2001 From: Kevin Sandow Date: Mon, 25 Jul 2022 20:07:14 +0200 Subject: [PATCH] Introduce constants for ping estimation and extract logging out of ping class --- client/index.ts | 8 +++++++- client/ping.ts | 52 ++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 48 insertions(+), 12 deletions(-) diff --git a/client/index.ts b/client/index.ts index ab83397..72e0cd0 100644 --- a/client/index.ts +++ b/client/index.ts @@ -11,7 +11,13 @@ const socket: ClientSocket = io(uri, { }, }) -new Ping(socket).start() +const ping = new Ping(socket) +ping.start() + +setInterval(() => { + // eslint-disable-next-line no-console + console.debug(`Ping: ${ping.average}ms ±${ping.delta}ms`) +}, 60000) socket.emit('characterList', (characters) => { // eslint-disable-next-line no-console diff --git a/client/ping.ts b/client/ping.ts index 9045e2b..0b0f048 100644 --- a/client/ping.ts +++ b/client/ping.ts @@ -1,5 +1,9 @@ import { ClientSocket } from './socket' +const initialDelay = 1000 +const delayBetweenPings = 10000 +const keepRecentPingCount = 10 + const avg = (values: number[]) => values.reduce((a, b) => a + b) / values.length export default class Ping { @@ -9,9 +13,18 @@ export default class Ping { readonly #pings: number[] + #average: number + + #delta: number + + #isDirty: boolean + constructor(socket: ClientSocket) { this.#socket = socket this.#pings = [] + this.#average = NaN + this.#delta = NaN + this.#isDirty = false } #update() { @@ -20,27 +33,44 @@ export default class Ping { this.#socket.emit('ping', () => { this.#pings.push(Date.now() - start) - while (this.#pings.length > 10) { + while (this.#pings.length > keepRecentPingCount) { this.#pings.shift() } - // TODO: make calculations on demand and extract/remove logging of ping - const ping = Math.round(avg(this.#pings)) - const delta = Math.round(avg(this.#pings.map((d) => Math.abs(d - ping)))) - - // eslint-disable-next-line no-console - console.debug( - `Ping: ${ping}ms ±${delta}ms (${JSON.stringify(this.#pings)})`, - ) + this.#isDirty = true }) - this.#timeout = setTimeout(this.#update.bind(this), 10000) + this.#timeout = setTimeout(this.#update.bind(this), delayBetweenPings) + } + + #updateCache() { + this.#average = Math.round(avg(this.#pings)) + this.#delta = Math.round( + avg(this.#pings.map((d) => Math.abs(d - this.#average))), + ) + this.#isDirty = false + } + + get average(): number { + if (this.#isDirty) { + this.#updateCache() + } + + return this.#average + } + + get delta(): number { + if (this.#isDirty) { + this.#updateCache() + } + + return this.#delta } start() { this.stop() - this.#timeout = setTimeout(this.#update.bind(this), 1000) + this.#timeout = setTimeout(this.#update.bind(this), initialDelay) } stop() {