window.clearInterval與window.setInterval的用法詳解

字號(hào):


    window.setInterval()
    功能:按照指定的周期(以毫秒計(jì))來調(diào)用函數(shù)或計(jì)算表達(dá)式。
    語法:setInterval(code,millisec)
    解釋:code:在定時(shí)時(shí)間到時(shí)要執(zhí)行的JavaScript代碼串。
    millisec:設(shè)定的定時(shí)時(shí)間,用毫秒數(shù)表示。
    返回值:定時(shí)器的ID值,可用于clearInterval()方法停止指定的定時(shí)器。
    注:setInterval()方法會(huì)不停地調(diào)用函數(shù),直到用clearInterval()終止定時(shí)或窗口被關(guān)閉。
    window.clearInterval()
    功能:取消由setInterval()方法設(shè)置的定時(shí)器。
    語法:clearInterval(id_of_setinterval)
    解釋:id_of_setinterval:由setInterval()返回的ID值。該值標(biāo)識(shí)了一個(gè)setInterval定時(shí)器。
    也就是:window.setInterval()返回的就是window.clearInterval的參數(shù)
    例子:
    <script type="text/javascript">
    var count = 0;
    var timeID;
    function timeCount()
    {
    document.getElementByIdx('timetxt').value = count;
    count++;
    }
    function beginCount()
    {
    timeID = setInterval("timeCount()",1000);
    }
    function stopCount()
    {
    clearInterval(timeID);
    }
    </script>
    <input type="button" value="開始計(jì)時(shí)" onclick="beginCount()" />
    <input type="text" id="timetxt" size="5" />
    <input type="button" value="停止計(jì)時(shí)" onclick="stopCount()" />
    再如:
    var objTimer = window.setInterval("moveDiv()",10)是調(diào)動(dòng)定時(shí)器,其中moveDiv是js的一個(gè)函數(shù)
    if(objTimer) window.clearInterval(objTimer)是停止定時(shí)器