什么是定時器?
定時器就是可以定時一段時間后執(zhí)行某些功能,或者每隔一段時間重復執(zhí)行某些功能。
定時器和循環(huán)的區(qū)別要尤其注意,循環(huán)結構內(nèi)部使用延時函數(shù)也可以實現(xiàn)定時器的重復執(zhí)行效果,但是如果使用循環(huán)加延時,程序是阻塞的,會一直停留在循環(huán)過程中,循環(huán)結構后面的程序無法執(zhí)行。即計算機資源一直處于被占用狀態(tài),消耗也很大。
定時器是只在觸發(fā)的時刻執(zhí)行指定功能,沒有到觸發(fā)時刻程序不會阻塞,按照順序,正常執(zhí)行定時器后面的程序。
setTimeout()
語法:
setTimeout(func,millisec)
參數(shù) | 描述 |
func | 要調(diào)用的函數(shù)后要執(zhí)行的 JavaScript 代碼串。 |
millisec | 在執(zhí)行代碼前需等待的毫秒數(shù)。 |
功能:在指定的毫秒數(shù)后調(diào)用函數(shù)。
setTimeout(function(){
alert("start");
}, 3000);
setInterval()
語法:
setInterval(func,millisec)
參數(shù) | 描述 |
func | 要調(diào)用的函數(shù)后要執(zhí)行的 JavaScript 代碼串。 |
millisec | 周期性執(zhí)行func的時間間隔,以毫秒計。 |
功能:按照指定的周期(以毫秒計)來調(diào)用函數(shù)或計算表達式。方法會不停地調(diào)用函數(shù),直到 clearInterval() 被調(diào)用或窗口被關閉。
setInterval(function(){
console.log("hioier.com");
}, 1000);
簡易計時器項目
實現(xiàn)一個計時器,綠色方框內(nèi)數(shù)字從0開始,每隔1s增加1。

<style>
#d1{
width:200px;
height:200px;
color:white;
font-size:100px;
background:green;
text-align:center;
line-height:200px;
}
</style>
<body>
<div id="d1">0</div>
<script>
let d1 = document.getElementById("d1");
let n = 0;
setInterval(function(){
d1.innerHTML = n++;
}, 1000);
</script>
</body>
跳躍墜落兩張圖片循環(huán)切換
例如:兩張圖片的名字分別為11.jpg和12.jpg,只需設置一個變量在11和12之間切換即可。

<style>
#d1 {
width: 500px;
height: 400px;
}
</style>
<body>
<img id="d1" src="images/11.jpg"/>
<script>
let d1 = document.getElementById("d1");
let n = 11;
setInterval(function(){
n++;
if(n > 12)
n = 11;
d1.src = `images/${n}.jpg`;
}, 500);
</script>
</body>
停止定時器,按下停止跳躍按鈕,停止跳躍。
<body>
<img id="d1" src="images/11.jpg"/>
<button id="btn_stop">停止跳躍</button>
<script>
let d1 = document.getElementById("d1");
let btn_stop = document.getElementById("btn_stop");
let n = 11;
let timer = setInterval(function(){
n++;
if(n > 12)
n = 11;
d1.src = `images/${n}.jpg`;
}, 500);
btn_stop.onclick = function(){
clearInterval(timer);
}
</script>
</body>
拆除炸彈
炸彈倒計時10s,如果沒有拆除就會爆炸,現(xiàn)在請你點擊按鈕拆除炸彈。

<style>
#d1 {
text-align: center;
}
#d3 {
width: 100px;
height: 100px;
color: white;
font-size: 50px;
background: green;
text-align: center;
line-height: 100px;
margin: 0 auto;
}
</style>
<div id="d1">
<button id="btn">
開始拆彈
</button>
<div id="d2">
<img src="images/7.gif"/>
<div>
<div id="d3">
10
</div>
</div>
</div>
</div>
<script>
let d3 = document.getElementById("d3");
let btn = document.getElementById("btn");
let n = 10;
let timer = setInterval(function(){
d3.innerHTML = n--;
if(n < 0){
alert("BOOM!");
n = 10;
}
}, 1000);
btn.onclick = function(){
clearInterval(timer);
alert("拆彈成功!");
}
</script>