[英]JS garbage collector - Clear timers when remove object
我的計時器有問題。 我知道如果我設置obj = nul;
或刪除對象delete obj;
它將從內存中刪除。 但是,如果我的對象中有間隔,那將不起作用。 delete
和obj = null;
不工作。 如何在不刪除已刪除對象中的情況下刪除計時器。
我認為Angular4僅清除將要刪除的組件中的那些計時器。 后台計時器無法刪除。
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);
對不起,英語。
似乎沒有辦法自動執行此操作。 您需要手動清除間隔。 您可以這樣定義一個類:
class TimerTask {
constructor(time){
this.id = setTimeout(() => this.run(), time);
}
run(){ /* override that in subclasses */ }
clear(){
clearTimeout(this.id);
}
}
所以可以做到:
class Log extends TimerTask {
run(){
console.log("done");
}
}
const test = new Log(1000);
然后在某個時候:
test = test.clear();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.