Here's a thought to consider: the "should" be garbage collected scenario might never actually occur, as the setInterval
function you've set up is keeping a reference to the object (referred to as this
in your case) indefinitely. It will require additional logic to determine if there's still a need to keep running it.
One suggestion I have, especially since you already have a defined get Latency()
, is to incorporate some monitoring logic within it to check if anyone has recently requested for the latency value. If the getter has been invoked recently, continue polling. Otherwise, stop the interval.
If you were to switch to using async getLatency()
instead, it could simplify things by allowing you to wait for the latency calculation upon detecting that no recent pings have occurred.
I'm sharing this code snippet purely for conceptual demonstration:
// Time delay before canceling the interval
const latencyTimeout = 200000;
// Inside your class
async getLatency(): number {
if (!this.latency) {
const started = Date.now();
const poller = setInterval(async () => {
if (Date.now() - started > latencyTimeout) {
clearInterval(poller);
this.latency = null;
}
this.latency = await this.ping();
}, 1000);
this.latency = await this.ping();
}
return this.latency;
}
On another note, you might want to reconsider using setInterval
and opt for a recurring setTimeout
instead. The issue with intervals is that they operate independently of the time taken to complete the ping process. For example, if your ping takes 500ms but you're polling every second, it may seem fine. However, if a ping lasts 2000ms, the order of received pings could become jumbled. Using setTimeout
ensures each ping only triggers after the previous one finishes, preventing potential confusion.