SoFunction
Updated on 2025-03-01

javascript removeChild memory leak


<html>
<head>
<title>Test the memory leak caused by removeChild</title>
</head>
<body>
<a href="javascript:leak();">Method of generating memory leaks</a>
<br />
<a href="javascript:notLeak();">No memory leak method</a>
</body>
</html>
<script>
var dialog;
function add()
{
dialog = ('div');
var html = '<div><p>Title</p></div>';
= html;
(dialog);
='200px';
='200px';
}
function remove()
{
(dialog);
dialog=null;
}
function leak()
{
for(var i=0;i<100000;i++){
add();
remove();
}
alert('leak done');
}
function notLeak()
{
for(var i=0;i<100000;i++){
add();
discardElement(dialog);
}
alert('notLeak done');
}
function discardElement(element) {
var garbageBin = ('IELeakGarbageBin');
if (!garbageBin) {
garbageBin = ('DIV');
= 'IELeakGarbageBin';
= 'none';
(garbageBin);
}
// move the element to the garbage bin
(element);
= '';
}
</script>