0

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.

1
  • A solution totally depends on how MyObject is used. Commented Nov 8, 2018 at 15:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.