How to completely destroy a JavaScript object?

9.9k views Asked by At

I am developing a game server with node.js, and I would want to store matchs inside a queue, in order to be able to destroy them after a certain timeout. Here is basically my implementation :

var matchs = [];

var createMatch = function () {
    matchs.unshift(new Match());
    matchs[0].start();

    setTimeout(function () {
        delete matchs[matchs.length - 1];
        matchs.pop();
    }, 5 * 1000);
};

function Match() {

    // ...

    this.foo = 0;

    this.start = function () {
        var self = this;

        setInterval(function () {
            console.log(self.foo++);
        }, 1 * 1000);
    };
}

What this code is supposed to do is, when I call createMatch(), display an increasing number every second, and stop after 5 seconds. However if I run this code, it will continue displaying numbers forever, which leads me to think that my Match objects are not destroyed properly.

Help please?

2

There are 2 answers

0
m4ktub On BEST ANSWER

The delete operator deletes a property but does not destroy an object nor any thing the object has created (like the interval). So your setTimeout could actually be:

setTimeout(function () {
    matchs.pop().destroy();
}, 5 * 1000);

The pop removes the element from the array (no longer referenced and can be cleaned) but the destroy() is needed to to explicitly tell the Match object it needs to clean things up. In Javascript there is no way to do something when the object is really deleted from memory. There is no such concept.

So your Match object is responsible for keeping track of things it needs to clean afterwards like the example bellow:

    function Match() {
    this.intervalId = undefined;

    this.start = function () {
        ...
        this.intervalId = setInterval(function () {
            ...
        }, 1 * 1000);
    };

    this.destroy = function() {
        if (intervalId)  {
            clearInterval(this.intervalId);
        }
    }
}

Timeouts and intervals are a resource that can be destroyed by the appropriate functions. In this case clearInterval().

2
Halcyon On

You can use clearInterval to clean up an interval.

var handle = setInterval(..);
clearInterval(handle);

Simply deferencing the Match object will not cause the interval to stop because it's still running. Additionally that interval will keep a reference to the Match through the self variable.