我的脚本需要12秒钟才能运行,但是稍后确切的脚本需要50毫秒才能运行?

问题描述

| 我有这段代码
<!DOCTYPE html><html><head>
<style>button{disabled:true;}</style>
<script>
var d;
function when_loaded(){
    d=document.getElementById(\"d\");
    //adding nested elements to d using different methods
    //basically just simulating a real situation
    document.title=\"loading..\";
    for(var x=0;x<3500;++x){
        d.appendChild( document.createElement(\"div\"));
        d.appendChild( document.createElement(\"div\")).innerHTML = \"asd\";
        d.appendChild( document.createElement(\"div\")).innerHTML = \"<a href=\'#\'>zxc</a><div>qwe</div>\";
        d.appendChild( document.createElement(\"span\")).innerHTML = \"asd\";
        d.appendChild( document.createElement(\"div\")).appendChild( document.createElement(\"span\")).appendChild( document.createElement(\"span\"));
    }
    document.title=\"loading done\";
    var del=document.getElementById(\"del\");
    var del2=document.getElementById(\"del2\");
    del.style.disabled=del2.style.disabled=\"false\";
}

function del(){
    document.title=\"deleting\";
    var a=new Date().getTime();
    d.innerHTML=\"\";
    var b=new Date().getTime();
    document.title=\"deleted\";
    alert(b-a+\" milli seconds taken\");
    document.body.innerHTML=\"you can refresh the page Now and try the other button\";
}

function del2(){
    document.title=\"deleting\";
    var a=new Date().getTime();
    var c;
    while(c=d.firstChild){
        d.removeChild(c);
    }
    var b=new Date().getTime();
    document.title=\"deleted\";
    alert(b-a+\" milli seconds taken\");
    document.body.innerHTML=\"you can refresh the page Now and try the other button\";
}
</script>
</head><body onload=\"when_loaded();\">
<button id=\"del\" onclick=\"del();\">del</button>
<button id=\"del2\" onclick=\"del2();\">del2</button>
<div id=\"d\"></div>
</body></html>
由于某种原因,当我第一次运行代码(在Windows Vista Home Premium的Chrome中)并按下第二个按钮时,运行该脚本花费了12秒钟。 但是在那之后,我试图重复我的情况。现在只需要50毫秒。 我关闭浏览器并重新打开它,仍然是50毫秒。 我重新启动计算机..仍然是50毫秒。 所以我的问题是,是否有人知道导致异常发生的原因以及如何复制异常? las,有人可以测试第二个按钮并发布所需的时间(0.05秒或12秒)     

解决方法

        如果只用了12秒一次,再也没有用了,那么只需将其放到其他占用CPU的应用程序中即可。     ,        永远不要在for循环中将元素附加到DOM。它总是不得不一遍又一遍地重画页面,从而导致性能降低。 您应该创建一个新元素作为包装器。将所有新元素追加到此元素。循环完成后,将其添加到页面。