Reputation: 1248
I am working on a little Websocket project (using Socket.io), where I use a class like that:
function myClass() {
// start server sync
window.setInterval(this.update.bind(this), 14);
// listen for socket.io events
io.on('my-event', doStuff);
}
There are multiple instances of that class stored in an array. After some time, the instances get deleted like that:
myArr.splice(index, 1);
The array is the only location, I store the instances in, so I thought, they would get deleted by the garbage collector after removing them from the array.
Instead I noticed, that they still respond to my websocket events. I am wondering if the interval prevents the object from getting deleted, because it is bound to the window object. Do I need to clear the interval before deleting the class instance?
Or does the event listener prevent the object from being deleted?
Upvotes: 2
Views: 945
Reputation: 1074989
...the instances get deleted like that:
myArr.splice(index, 1);
...Instead I noticed, that they still respond to my websocket events. I am wondering if the interval prevents the object from getting deleted, because it is bound to the window object. Do I need to clear the interval before deleting the class instance?
Yes, you need to do more cleanup. You need to:
Clear the interval, to clean up resources associated with it and make it release its reference to the function created by this.update.bind(this)
(which in turn has a reference to the object, keeping it in memory).
Remove any event listeners (e.g., web socket events), which will remove their references to the event handler functions, which probably have references to the object that keep it in memory.
Ensure that any other references to the object, direct or indirect (such as in any other bound functions) are also released.
Upvotes: 3
Reputation: 382284
Yes, referring to a value or a scope from a function prevents its garbaging.
In fact pointers from functions to objects and scopes are one of the main causes of memory leaks in JavaScript, the most frequent one in this category being the closures, often related to event callbacks (including timers in that category).
When you want your object to be garbageable, be sure to unregister all event handlers, and to delete timers (note that event handlers are deleted when you remove the element from the DOM and don't keep a reference to it).
Upvotes: 0