Reputation: 2879
I know javascript does not have destroy method, but my object needs to know when it ceases to exist.
class MyObject
{
constructor()
{
this.interval = setInterval(this.checker, 5000);
}
checker()
{
// Stuff
}
beforeDestroy()
{
clearInterval( this.interval );
}
}
I would like to clear a timeout and an interval before it's being destroyed. I'm not finding it, I'm assuming it is not possible but I would like to be sure. Any node.js version, experimental or using custom module is ok.
Upvotes: 0
Views: 1538
Reputation: 222760
Cause and effect relationship is mixed up here. It's not possible to determine the moment of time when MyObject
instance is destroyed. Usually objects that aren't referenced anymore can be garbage-collected.
beforeDestroy
is usually implemented by frameworks as a hook, e.g. AngularJS $onDestroy
, Angular ngOnDestoy
, React componentWillUnmount
. A place that is responsible for MyObject
instantiation should also be responsible for calling beforeDestroy
when it's known that an instance is not needed anymore. Then an instance can be garbage-collected.
Upvotes: 1