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 pletely?
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 pletely?
-
setInterval
will keep running until you callclearInterval
, so callclearInterval
when you are done with it. – Matt Burland Commented Sep 3, 2015 at 20:12 - 3 Did you already check out this? – David Commented Sep 3, 2015 at 20:14
- I don't think It will destroy its prototype methods by clearing out the instance, if that's what you are after. – MinusFour Commented Sep 3, 2015 at 20:16
- Thank you @David, But I think setTimeout is not the only reference affecting garbage collector's work. – Reyraa Commented Sep 3, 2015 at 20:49
2 Answers
Reset to default 3These are items I know you should do:
- All the functions passed to
setInterval
andsetTimeout
must have declaration so you can remove them by making equal tonull
. - Use
clearInterval
andclearTimeout
for all of them. - All the closures inside your methods must have declaration - must not be anonymous - in order to be removed.
- Make sure you haven't used global variables in so that your methods and closures retain the reference to it.
- in the last step make the instance itself equal to null.
hope it covers all you need.
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;