day27—JavaScript實現定時器及其應用案例

來源:互聯網
上載者:User

標籤:second   star   bsp   分享圖片   script   hello   info   ESS   點擊   

轉行學開發,代碼100天——2018-04-12

 

JavaScript中定時器有兩種,分別是setInterval和setTimeout;其用法如下:

開啟:

 setTimeout("function",time) 設定一個逾時對象;順延強制;只執行一次

setInterval("function",time) 設定一個逾時對象;連續執行;重複執行

 

*上述兩種方法,均有傳回值,即改定時器對象。該對象可作為關閉對象輸入。

關閉:

clearTimeout(對象) 清除已設定的setTimeout對象 
clearInterval(對象) 清除已設定的setInterval對象 

如window對象的開啟及關閉

var timer = window.setInterval(express,millseconds);

window.clearInterval(timer);

var timer = window.setTimeout(express,millseconds);
window.clearTimeout(timer);

 

定時器啟停用例:

設定兩個按鈕,分別控制定時器的開啟和關閉

<input type="button" name="start" id="btn1" value="start"><input type="button" name="stop" id="btn2" value="stop">

JavaScript實現定時器的啟停控制

<script type="text/javascript">         //定時器用法        // var timer = window.setInterval(express,millseconds);window.clearInterval(timer);        //     var timer = window.setTimeout(express,millseconds);        //     window.clearTimeout(timer);        window.onload = function () {            var btn1 = document.getElementById("btn1");            var btn2 = document.getElementById("btn2");            var timer = null;            btn1.onclick =function(){                timer =setInterval(function()                {                  alert("hello");                        },1000);            };            btn2.onclick = function(){                clearInterval(timer);            };                    }    </script>

點擊“start”按鈕,每隔一秒彈出提示框“hello”,即定時器開啟;點擊“stop”按鈕,提示框不再彈出,即定時器關閉。

 

day27—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.