简体   繁体   中英

JS garbage collector - Clear timers when remove object

I have a problem with timers. I know that if I set obj = nul; or delete object delete obj; it will removed from memory. But it not works if I have interval in my object. delete and obj = null; not working. How to delete a timers without doing this in the deleted object.

I think Angular4 clear only those timers from component that will be removed. Background timers not remove.

function MyFunc() {
  setInterval(function () {
    console.log('Interval');
  }, 1000);
}

var obj = new(MyFunc.bind({
  message: 'some_message'
}));

// From some time remove object
setTimeout(function() {
  delete obj;
  console.log('Delete object');
}, 5000);

Sorry for english.


Seems there is no way to do this automatically. You need to clear the interval manually. You might define a class like this:

class TimerTask {
  constructor(time){
    this.id = setTimeout(() => this.run(), time);
  }

 run(){ /* override that in subclasses */ }

  clear(){
    clearTimeout(this.id);
  }
}

So one can do:

class Log extends TimerTask {
  run(){
    console.log("done");
  }
}

const test = new Log(1000);

Then somewhen:

test = test.clear();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM