Home >Web Front-end >JS Tutorial >A good example of js memory leak_javascript skills

A good example of js memory leak_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:10:121190browse

I changed 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 is needless to say.

Run the code

Copy the code The code is as follows:

< H.tml & gt;
& lt; head & gt;
& lt; title & gt; memory leak & lt;/title & gt;
& lt; style & gt;
body {
padding: 10px; 10px;
} & lt ;/style>



<script><br> var q = [];<br> var n = 0 ;<br> setInterval(function(){<br> q.push(makeSpan());<br> if(q.length>=10){<br> var s = q.shift();<br> if(s){<br> s.parentNode.removeChild(s);<br> }<br> }<br> n ;<br> },10);<br><br> function makeSpan(){<br> var s = document.createElement("span");<br> document.body.appendChild(s);<br> var t=document.createTextNode("*** " n " ***");<br> s.appendChild(t);<br> s.onclick=function(e){<br> s.style.backgroundColor="red";<br> alert(n);<br> } ;<br> return s;<br> };<br> </script>



So how to solve it in IE? When deleting a node, manually break the circular reference and slightly change the setInterval code as follows:


Copy the code The code is 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);

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn