takayama
takayama

Reputation: 51

how to create a destructor in es6

For example:

function a() {
    this.heartbeat = setInterval(()=>{}, 10000)
}

var b = new a()
delete b //The heartbeat still seems to be working

I want to remove the heartbeat when my object is deleted.

Upvotes: 0

Views: 2231

Answers (1)

Eliya Cohen
Eliya Cohen

Reputation: 11458

Since there's no "built-in" destructor method of class in JavaScript, you can implement one for yourself (I'm sure that there's more options, but that's the only way I can think of):

class A {
  heartbeat = setInterval(() => console.log('hearbeat'), 1000);

  destroy() {
    clearInterval(this.heartbeat);
  }
}

let a = new A();

setTimeout(() => a.destroy(), 5000);

Upvotes: 0

Related Questions