Skip to content

Commit

Permalink
Introduce constants for ping estimation and extract logging out of pi…
Browse files Browse the repository at this point in the history
…ng class
  • Loading branch information
kevinsandow committed Jul 25, 2022
1 parent caa811a commit 52c60d0
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 12 deletions.
8 changes: 7 additions & 1 deletion client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
52 changes: 41 additions & 11 deletions client/ping.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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() {
Expand All @@ -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() {
Expand Down

0 comments on commit 52c60d0

Please sign in to comment.