什么是定時(shí)器?
定時(shí)器就是可以定時(shí)一段時(shí)間后執(zhí)行某些功能,或者每隔一段時(shí)間重復(fù)執(zhí)行某些功能。
定時(shí)器和循環(huán)的區(qū)別要尤其注意,循環(huán)結(jié)構(gòu)內(nèi)部使用延時(shí)函數(shù)也可以實(shí)現(xiàn)定時(shí)器的重復(fù)執(zhí)行效果,但是如果使用循環(huán)加延時(shí),程序是阻塞的,會(huì)一直停留在循環(huán)過(guò)程中,循環(huán)結(jié)構(gòu)后面的程序無(wú)法執(zhí)行。即計(jì)算機(jī)資源一直處于被占用狀態(tài),消耗也很大。
定時(shí)器是只在觸發(fā)的時(shí)刻執(zhí)行指定功能,沒(méi)有到觸發(fā)時(shí)刻程序不會(huì)阻塞,按照順序,正常執(zhí)行定時(shí)器后面的程序。
setTimeout()
語(yǔ)法:
setTimeout(func,millisec)
參數(shù) | 描述 |
func | 要調(diào)用的函數(shù)后要執(zhí)行的 JavaScript 代碼串。 |
millisec | 在執(zhí)行代碼前需等待的毫秒數(shù)。 |
功能:在指定的毫秒數(shù)后調(diào)用函數(shù)。
setTimeout(function(){
alert("start");
}, 3000);setInterval()
語(yǔ)法:
setInterval(func,millisec)
參數(shù) | 描述 |
func | 要調(diào)用的函數(shù)后要執(zhí)行的 JavaScript 代碼串。 |
millisec | 周期性執(zhí)行func的時(shí)間間隔,以毫秒計(jì)。 |
功能:按照指定的周期(以毫秒計(jì))來(lái)調(diào)用函數(shù)或計(jì)算表達(dá)式。方法會(huì)不停地調(diào)用函數(shù),直到 clearInterval() 被調(diào)用或窗口被關(guān)閉。
setInterval(function(){
console.log("hioier.com");
}, 1000);簡(jiǎn)易計(jì)時(shí)器項(xiàng)目
實(shí)現(xiàn)一個(gè)計(jì)時(shí)器,綠色方框內(nèi)數(shù)字從0開(kāi)始,每隔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,只需設(shè)置一個(gè)變量在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>
停止定時(shí)器,按下停止跳躍按鈕,停止跳躍。
<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>
拆除炸彈
炸彈倒計(jì)時(shí)10s,如果沒(méi)有拆除就會(huì)爆炸,現(xiàn)在請(qǐng)你點(diǎ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">
開(kāi)始拆彈
</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>