简体   繁体   English

JS垃圾收集器-删除对象时清除计时器

[英]JS garbage collector - Clear timers when remove object

I have a problem with timers. 我的计时器有问题。 I know that if I set obj = nul; 我知道如果我设置obj = nul; or delete object delete obj; 或删除对象delete obj; it will removed from memory. 它将从内存中删除。 But it not works if I have interval in my object. 但是,如果我的对象中有间隔,那将不起作用。 delete and obj = null; deleteobj = 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. 我认为Angular4仅清除将要删除的组件中的那些计时器。 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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