我正在尝试使用DOM元素来显示动态可变数据(添加/删除它们)。我发现几乎所有的浏览器都有一个非常奇怪的行为:在我删除一个DOM元素然后添加一个新的元素之后,浏览器不会释放被删除DOM项占用的内存。请看下面的代码以了解我的意思。运行此页面后,它将逐步消耗高达150 MB的内存。有人能解释这种奇怪的行为吗?或者我做错了什么吗?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<script type="text/javascript">
function redrawThings() {
// Removing all the children from the container
var cont = document.getElementById("container");
while ( cont.childNodes.length >= 1 ) {
cont.removeChild(cont.firstChild);
}
// adding 1000 new children to the container
for (var i = 0; i < 1000; i++) {
var newDiv = document.createElement('div');
newDiv.innerHTML = "Preved medved " + i;
cont.appendChild(newDiv);
}
}
</script>
<style type="text/css">
#container {
border: 1px solid blue;
}
</style>
</head>
<body onload='setInterval("redrawThings()", 200);'>
<div id="container"> </div>
</body>
</html>
setInterval
函数:“出于与使用 eval() 相同的原因,不建议使用这种语法。” - Marcel Korpel