Does setInterval inside an object prevent garbage collection, when the object is deleted?

99封情书 提交于 2020-01-15 06:24:27

问题


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?


回答1:


...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.




回答2:


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).



来源:https://stackoverflow.com/questions/41429030/does-setinterval-inside-an-object-prevent-garbage-collection-when-the-object-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!