bhushan deshmukh
bhushan deshmukh

Reputation: 75

delete object instance of a class- NodeJS

i have created the class , and initialised it, also i have added the timer function inside the class, then i explicitly called class instance to null, still that timer function is running, my question is how do i delete the class instance from memory? , and how do i invalidate timer after class is null

my code is as follows

class Person {
    constructor() {
      this.id = 'id_1';
    }
    timers(){
    const intervalObj = setInterval(() => {
        console.log('interviewing the interval');
      }, 3000);
    }
  }

  var justAGuy = new Person();
  justAGuy.timers()
  justAGuy = null

Upvotes: 1

Views: 1443

Answers (1)

jfriend00
jfriend00

Reputation: 707706

Javascript is a garbage collected language. You don't and can't explicitly delete objects. Instead, you clear any references to the object so that no code can ever reach the object. That will make it eligible for garbage collection and the garbage collector will then remove it from memory on a future GC pass.

In your object, you also have to stop the interval timer because as long as it is running, then your object may be kept alive because the timer callback has access to this which refers to the object.

class Person {
     constructor() {
       this.id = 'id_1';
     }
     timers(){
        stop();
        this.intervalObj = setInterval(() => {
            console.log('interviewing the interval');
        }, 3000);
     }
     stop() {
         if (this.intervalObj) {
             clearInterval(this.intervalObj);
             this.intervalObj = null;
         }
     }

}

var justAGuy = new Person();
justAGuy.timers();
justAGuy.stop();
justAGuy = null;

Upvotes: 2

Related Questions