返回列表

setTimeout和setInterval效率对比,貌似差异不大

默认分类 2013/11/25 17:58

setTimeout和setInterval效率对比,貌似差异不大,代码如下

<script type="text/javascript">
<!--
var t1,t2,t3,t4;

var m = 0;
function mm() {
    m++;
    if (m<1000) {
        window.setTimeout('mm()', 1);
    }
    else {
        t2 = new Date();
        alert(1);

    }
}

var n = 0;
function nn() {
    n++;
    if (n>999) {
        t4 = new Date();
        window.clearInterval(c);
        alert(2);
    }
}

var c;
function doit1(){
    //todo
    alert(0);
    t1 = new Date();
    mm();
}
function doit2(){
    //todo
    alert(0);
    t3 = new Date();
    c = window.setInterval('nn()', 1)
}
function doit3(){
    //todo
    alert('setTimeout:'+(t2.getTime()-t1.getTime()));
    alert('setInterval:'+(t4.getTime()-t3.getTime()));
}


//-->
</script>

<button type="button" onclick="doit1()">setTimeout</button>
<button type="button" onclick="doit2()">setInterval</button>
<button type="button" onclick="doit3()">view result</button>