I modified someone else's example and I think it's more compact like this! To paraphrase other people's words, when a DOM object contains a reference to a Js object (such as an Event Handler), and this Js object holds a reference to the DOM object, a circular reference is enough, so under ie A memory leak occurred. Click "Run Code" and open Task Manager to see the memory changes. Tested under ie8 and ff respectively, the difference goes without saying.
run code
Copy the code code as follows:
<html>
<head>
<title>Memory leak</title>
<style>
body{
padding: 10px;
}
</style>
</head>
<body>
</body>
<script>
var q = [];
var n = 0;
setInterval(function(){
q.push(makeSpan());
if(q.length>=10){
var s = q.shift();
if(s){
s.parentNode.removeChild(s);
}
}
n++;
},10);
function makeSpan(){
var s = document.createElement("span");
document.body.appendChild(s);
var t=document.createTextNode("*** " + n + " ***");
s.appendChild(t);
s.onclick=function(e){
s.style.backgroundColor="red";
alert(n);
};
return s;
};
</script>
</html>
So how to solve it under ie?
When deleting a node, manually break the circular reference and slightly change the setInterval code inside as follows:
Copy the code code as follows:
setInterval(function(){
q.push(makeSpan());
if(q.length>=10){
var s = q.shift();
if(s){
s.onclick = null;//The key is here
s.parentNode.removeChild(s);
}
}
n++;
},10);