Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add/remove listeners on javascript ( garbage collector )

I have a quick question regarding on adding/removing listeners of a DOM object. I would like to ask if the garbage collector be able to collect the memory when removing elements from the page.

Example: a <ul> tag with a couple list of children(<li>)

var ul = document.getElementById('someParent');
var children = ul.children;
var someFunction = function() {};

for(var i = 0; i < children.length; i++) {
  children[i].addEventListener('click', someFunction);
}


// This is where I am not sure, would the garbage collector be able to collect
// the memory allocated on adding listener on children,
// if I remove the ul tag?
ul.remove();
like image 211
olanchuy Avatar asked Feb 02 '15 07:02

olanchuy


1 Answers

The line ul.remove(); will remove ul element and all of its children from the DOM. But memory for event listeners will not be released as long as you have references to those listeners, li elements, and ul element. Which you do have in variables children, someFunction and ul.

If you want to let the garbage collector clean all of these, you can do for example:

ul.remove();
children = null;
someFunction = null;
ul = null;

That way variable children will not hold the reference to those elements, and if you don't have any other variable in your code that hold the reference for those elements, garbage collector will collect them. The same holds for someFunction. Note that ul element holds all the references to its children and listeners, so ul has to be cleaned as well.

like image 107
Luka Avatar answered Sep 29 '22 23:09

Luka