Reputation: 4274
I have a class with many methods in its prototype
and I want to destroy its instance after it's done.
This answer tells how to destroy an instance of a class but I'm not sure which variables and/or other types of references I may have in the instance and it's methods that prevents it from removing by garbage collector.
I know I need to remove closures like the functions passed to setInterval
. What would be a list of possible items I need to do to destroy the instance completely?
Upvotes: 2
Views: 10193
Reputation: 9294
Set interval will continue running because it can not free the instance (of A) due to a closure to the A function which is the constructor of the class. Therefore you need to create a dispose pattern in order to free all the resources that the garbage collector can not free. After that the instance would be freed by the garbage collector when it is not used anymore.
function A() {
this.timerId = setInterval(function(){
console.log("A");
}, 2000)
}
A.prototype.dispose = function() {
clearInterval(this.timerId);
};
var instance = new A();
/* Will not work
instance = null;
*/
instance.dispose();
instance = null;
Upvotes: 1
Reputation: 356
These are items I know you should do:
setInterval
and setTimeout
must have declaration so you can remove them by making equal to null
.clearInterval
and clearTimeout
for all of them.hope it covers all you need.
Upvotes: 3