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?
The
delete
operator deletes a property but does not destroy an object nor any thing the object has created (like the interval). So yoursetTimeout
could actually be:The
pop
removes the element from the array (no longer referenced and can be cleaned) but thedestroy()
is needed to to explicitly tell theMatch
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:Timeouts and intervals are a resource that can be destroyed by the appropriate functions. In this case
clearInterval()
.