2010年7月15日 星期四

關於討論 jscript memory leak 的文章

http://www.crockford.com/javascript/memory/leak.html

function purge  用來消除 element 已防止 memory leak .


<html>
<head><title>Queue Test 3</title>
</head>
<body>
<p>
Queue Test 3 adds an event handler to each span, and removes it when
finished. See <a href="http://www.crockford.com/javascript/memory/leak.html">http://www.crockford.com/javascript/memory/leak.html</a>
</p>
<script>
/*global onunload, setTimeout */
(function (limit, delay) {
var queue = new Array(10);
var n = 0;

function makeSpan(n) {
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;
}

function purge(d) {
var a = d.attributes, i, l, n;

if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}

function process(n) {
queue.push(makeSpan(n));
var s = queue.shift();
if (s) {
purge(s);
s.parentNode.removeChild(s);
}
}

function loop() {
if (n < limit) {
process(n);
n += 1;
setTimeout(loop, delay);
}
}
onunload = function (e) {
purge(document.body);
};

loop();
})(10000, 10);
</script>

</body>
</html>

【下列文章您可能也有興趣】

沒有留言: