I am reading an online JavaScript tutorial in which is claimed the following code will cause memory leak in IE earlier than version 8.
function setHandler() {
var elem = document.getElementById('id')
elem.onclick = function() { /* ... */ }
}
The author also provided the fix to prevent the memory leak:
function setHandler() {
var elem = document.getElementById('id')
elem.onclick = function() { /* ... */ }
elem=null;
}
Why does the original code cause a memory leak and how does the fix prevent it?
The article gives a good explanation, the problem is IE and circular references.
That means that when you do:
the first line of the function is refencing the second, and the second is referencing the first and that causes IE to not free the memory it allocated to create the elem variable.
You are breaking the reference by explicitly removing the second reference, by “destroying” the value of elem, in the line
so IE can free the memory
The second reference happens because there is a problem with a closure, the inner function bound in the onclick has access to
elem(it exists in the function scope), so it’s “locked” there.In other words a there are two references to elem, one created in the var statement and one is made in the onclick function, and that reference won’t be released until the closure is released.
You can find more info here, here and in this stack overflow answer