A good example of a JS memory leak _javascript Tips

Source: Internet
Author: User

I have changed the example of others, I think this is more compact to write! In other words, when a DOM object contains a reference to a JS object (for example, an event Handler), and this JS object holds a reference to this Dom object, a circular reference is made, and a memory leak occurs under IE. Click "Run Code" and open Task Manager to see memory changes. Separately in IE8 and FF under the test, the gap does not need to say more.

Run code

Copy Code code as follows:

<title>memory leak</title>
<style>
body{
padding:10px;
}
</style>
<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>

then in IE how to solve it?

When deleting a node, manually break the ring reference and change the SetInterval code slightly below:

Copy Code code as follows:

SetInterval (function () {
Q.push (Makespan ());
if (q.length>=10) {
var s = q.shift ();
if (s) {
S.onclick = null;//key is here
S.parentnode.removechild (s);
}
}
n++;
},10);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.