javascript 定時器使用

來源:互聯網
上載者:User

標籤:

定時器的使用場合

setInterval() 方法,按照指定的周期(以毫秒記)來調用函數或計算運算式
setInterval() 方法會不停的調用函數,知道 clearInterval() 被調用或視窗被關閉,由setInterval() 返回的ID值可作用於 clearInterval() 方法的參數
setInterval(code,millisec)code 要調用的函數或執行的代碼,millisec 周期調用或調用code之間的時間間隔(以毫秒記)
傳回值: 一個可以傳遞給 window.clearInterval() ,從而取消對code的周期性執行的值

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>test測試例子</title><script type="text/javascript">// setInterval() 測試例子var i = 0;var int = setInterval(function(){console.log(i++);}, 1000)function stop(){clearInterval(int);console.log("ok");}</script></head><body><input type="button" value="停止" onclick="stop();"></body></html>

 

setTimeout() 方法,在指定的毫秒數後調用函數或計算運算式
setTimeout(code,millisec)code 要執行的函數活執行的代碼,millisec 在執行代碼前需等待的毫秒數
注意:setTimeout() 只執行code一次,如果要多次調用,請使用 setInterval() 或者讓code 自身再次調用 setTimeout()

clearTimeout(id_of_setTimeout) 取消setTimeout() 設定的timeout, id_of_setTimeout 是 setTimeout() 返回的id

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>test測試例子</title>    <script type="text/javascript">    // setTimeout() 測試例子        var i = 0;    var t;    function time5(){        t = setTimeout(function(){            console.log(i++);            time5();        },1000);    }    function stop(){        clearTimeout(t);        console.log("okl");    }    time5();    </script></head><body>    <input type="button" value="清除定時器" onclick="stop();"></body></html>

 

javascript 定時器使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.