<html> <body> <script type="text/javascript"> document.write("Program to illustrate memory leak via closure"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction(){ alert("Hi! I will leak"); }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); // This is used to make the leak significant }; // called later in your code function freeObject() { var obj = document.getElementById("element"); obj.parentNode.removeChild(obj); // remove object from DOM }; </script> <button id="element">Click Me</button> </body> </html>
Now, you've removed the object from the DOM (sometime later in your code) and probably expected all memory associated with it to be freed, but the circular reference keeps that from happening in IE6. You could work-around that by doing the following:
<html> <body> <script type="text/javascript"> document.write("Program to illustrate memory leak via closure"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction(){ alert("Hi! I will leak"); }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); // This is used to make the leak significant }; // called later in your code function freeObject() { var obj = document.getElementById("element"); obj.onclick=null; // clear handler and closure reference obj.parentNode.removeChild(obj); // remove object from DOM } </script> <button id="element">Click Me</button> </body> </html>
or, if you don't need the obj reference in the closure, you could null the reference from the closure entirely with this:
<html> <body> <script type="text/javascript"> document.write("Program to illustrate memory leak via closure"); window.onload=function outerFunction(){ var obj = document.getElementById("element"); obj.onclick=function innerFunction(){ alert("Hi! I will leak"); }; obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX")); // This is used to make the leak significant obj = null; // kills the circular reference, obj will be null if you access if from innerFunction() }; </script> <button id="element">Click Me</button> </body> </html>