Im wondering how to properly “Clear” a object instance.
With the code below, the internal setInterval() will continue to run even after the instance is “cleared” by the parent.
// simple Class
var aClass = function(){
return {
init: function(){
console.log("aClass init()")
setInterval( this.tick, 1000 );
// note: we're not storing the ref
},
tick: function(){
console.log("aClass tick");
}
}
}
// instantiate the class
var inst = new aClass();
inst.init();
// try to forget the instance
function test(){
console.log("test() 1 inst:", inst);
inst = null;
console.log("test() 2 inst:", inst);
}
// run for a while, then call test()
setTimeout( test, 4000 );
Output:
aClass init()
aClass tick
aClass tick
aClass tick
test() 1 inst: {.....}
test() 2 inst: null
aClass tick
aClass tick ...
Problem is that the “aClass tick” message continues to print after the test().
Ideas?
Your instance is being kept in memory because the function you passed to
setIntervalis being kept in memory and has a reference to it. That function is referenced by the browser’s list of active interval timers.You’ll need to remember the interval handle:
…then later when you’re dropping your reference to
inst, you’ll want to tell it that:…and in
inst.cleanup:That way, the browser will remove its reference to the function you passed to
setInterval, which means that function will become eligible for garbage collection (based on your code there are no other references to it). And that means the reference it has to your instance is released, and so if no other outstanding references to that instance exist, it’s eligible for garbage collection.