How can we stop the interval when the object is no longer in use?

I am working on a client class that communicates with a server via WebSocket. I want to set up a system that regularly pings the server to measure latency. However, I'm worried that using setInterval within the class might cause issues if it continues to ping even after the object is no longer needed. How can I determine when to use clearInterval?

Here's a brief overview of the code snippet:

class WSClient extends EventEmitter
{
    private latency: number;
    public get Latency(): number
    { return this.latency; }

    public async ping(): Promise<number>
    { ... }

    public constructor(options)
    {
        super();

        // Initialize constructor

        setInterval(() => this.ping().then(latency => this.latency = latency), 1000);
    }
}

Answer №1

If you want to implement a setInterval() and store it in a variable, you can do so by following these steps:

class WebSocketClient extends EventEmitter
{
    private connectionLatency: number;
    public get Latency(): number
    { return this.connectionLatency; }

    public async checkConnection(): Promise<number>
    { ... }

    public constructor(options)
    {
        super();

        // Perform necessary actions in the constructor

        this.connectionInterval = setInterval(() => this.checkConnection()
        .then(latency => this.connectionLatency = latency), 1000);
    }
}

Once you no longer need the interval running, you can stop it as follows:

WebSocketClient.connectionInterval.clearInterval();

Answer №2

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to simulate a static variable in JavaScript unit testing?

After running the karma coverage test, I achieved a coverage of 99.3%. To reach 100%, I require assistance in testing the else part of the function below: createCurrencyUnits(): void { var keys = Object.keys(ObjectsDomainConstants.CURRENCY_UNITS); for (va ...

Leveraging Angular for dynamic HTML form type setting

I've been experimenting with Angular in order to create a form that includes all the properties of an object. Among these properties are passwords, and I want Angular to utilize the password form type for them. Currently, I have managed to make it wo ...

Unable to bind jquery click event to bootstrap col-md div

I am facing an issue with a div element that is defined as follows: <div class="col-md-4 single-signup wow fadeIn animated" data-wow-offset="10" data-wow-duration="1.5s"> Within this div, there is some content, like the following: <p><a i ...

The issue arose as a result of a SQLITE_ERROR, specifically mentioning that the Users table does not exist. However, the model has been

Greetings! I am currently facing an issue while trying to integrate the "sequelize-typescript" library into my Express.JS REST API that I developed using Dependency Injection. The error I am encountering is: SQLite Error: no such table: Users Below is th ...

Combining two sequential API requests in a cascading manner

I am attempting to verify endpoint availability by chaining two API requests and passing the token generated from the first request into the authorization header of the second request. Despite successfully generating the token, the second API is unable to ...

Enhancing Nested Objects using Mongoose

When attempting to update nested objects using Mongoose, the request I receive appears like this: { 'example[apple]': 'false', 'example[pear]': 'false', 'example[banana]': 'false', 'example[ ...

Is the new Angular 2 CLI tool incorporating Systemjs?

Seeking Answers Curious about the absence of systemjs.config.js file when using the new Angular2 CLI setup tool. Is there a way to install a basic version of Angular 2 without relying on the CLI tool available on angular.io? Past Experience In the past, ...

Tips for Fixing the JSON Error in Firefox

My Response Header consists of: Access-Control-Allow-Meth... GET, POST Access-Control-Allow-Orig... * Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Connection Keep-Alive Content-Length 81 Content-Type text/html ...

Is it possible to activate the onChange function even when the input value is automated?

I am using a Form.Input element <Form.Input fluid required label="First name" placeholder="Jose" name="firstName" value={ _.isNil(selectedProfile) ? firstName : selectedProfile.first_name } onChange={this.onCustomerFieldUpdate} /> In my code, I am ...

What is the method for aligning an object perpendicular to a surface in Three.js?

Check out this relevant codepen: http://codepen.io/OpherV/pen/yNebep In the game I am working on, there is a unique alien tree model. To create spikes on each face of the tree, I am generating pyramids using CylinderGeometry with 4 faces and positioning ...

Error message: Unable to locate module (webpack)/hot/emitter when running ionic serve with Ionic 4

Current Technology Stack: Node v10.15.1 Ionic 4.10.1 Upon running ionic serve, an error is encountered: ERROR in (webpack)/hot/emitter.js [ng] Module not found: Error: Can't resolve 'events' in '/zazou/node_modules/@angular-de ...

Running the NPM build command results in an error specifically related to an HTML file

I encountered an issue in my AngularJS application when running the command: npm run build -- -prod The error message I received was: ERROR in ng:///home/directoryling/appname-play.component.html (173,41): The left-hand side of an arithmetic operation ...

JS unable to insert new row in table

I checked the input value before submitting it in the form and confirmed that it is correct, returning as a string.enter image description here const saveList = () => { const inputListNameText = inputListName.value; fetch('/api/lists' ...

Puppeteer: Locating elements using HTML attributes

I'm currently working on getting Puppeteer to locate an element on this webpage using its attribute data-form-field-value, which needs to match 244103310504090. Here is the HTML code for the button in question: <section class="fl-accordion-tab--c ...

The feature of determining if an edge exists, within the dagre-d3/graphlib,

Has anyone utilized the graph.hasEdge function in dagre-d3/graphlib to check for the existence of an edge between two nodes? This API takes two arguments representing the two nodes and verifies if there is an edge connecting them. I am facing an issue whe ...

Following the upgrade to J-Query 3.x, the function Date.today is no longer supported

Recently, I updated my local jQuery library from version 1.9.1 to 3.6.0 and encountered some unexpected issues. Despite searching online, I could not find any solutions for these problems. The errors seem to be related to standard JavaScript functions rath ...

Coordinate Point Visualization in Three.js CameraHelper

Looking to control the rendering volume of a camera in three.js and obtain the control point. You can achieve this by using a camera helper similar to the example provided in the camera example with the pointMap attribute. console.log(cameraOrthoHelper.p ...

Error parsing PHP string arrays into JavaScript string arrays

My attempts to convert a name string array from PHP to Javascript have been unsuccessful. var name = <?php echo json_encode($eventname); ?>; and var name = new Array("<?php echo implode('","', $eventName);?>"); I expected the ou ...

Modify JointJS/Rappid inspector or cell model value without relying on the inspector

Recently, I've encountered a challenge in updating the value of a text attribute (name) in a cell model without resorting to the use of the inspector. My goal is for this update to not only reflect in the inspector field but also in the linked cell mo ...

Manipulating elements repeatedly using jQuery

One of the issues I encountered while working with jQuery was appending a YouTube video when a button is clicked. To do this, I used the following code: onclick="$('#videogallery').append('<iframe width=725 height=398 src=http://www.yout ...