標籤: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實現定時器及其應用案例