定時器是一個簡單的異步機制
setInterval(): 是一個隔一段時間就執行一次的循環執行的方法。方法可按照指定的週期(以毫秒計)來調用函數或計算表達式。這個方法會一直調用函數,直到clearInterval()被調用或窗口被關閉才停止調用函數。由setIntrval() 返回的 id 值可用作clearInterval() 方法的參數。
setTime():是一個延遲函數,等過了一段時間就執行,僅執行一次。
例:這是一個js實現css的動畫的過程,(在不使用css的animation 情況下)
<div id="fade-obj" style="width:300px;height:300px;background:#000"></div>
<button id="fade-btn">淡出</button>
<script>
var fade=document.querySelector("#fade-obj");//這是一個
var fadeBtn=document.querySelector("#fade-btn");
var id;
var seed=100;
fadeBtn.onclick=function () {
if (this.innerHTML=="淡出"){
this.innerHTML="淡入";
/*因爲fadeIn(),fadeOut無返回值,所以只需寫函數名,不需要括號。不然,setInterval()只會執行一次;*/
id=setInterval(fadeIN,10)
}else {
this.innerHTML="淡出";
id=setInterval(fadeOut,10);
}
}
function fadeIN() {
fadeBtn.disabled=true;
seed--;
console.log("fadeIN(): "+seed);
fade.style.cssText="width:300px;height:300px;background:#000;opacity:"+seed/100+";";
if (seed==0){
window.clearInterval(id);//傳入setInterval的返回值
fadeBtn.disabled=false;
}
}
function fadeOut() {
fadeBtn.disabled=true;
seed++;
console.log(seed);
fade.style.cssText="width:300px;height:300px;background:#000;opacity:"+seed/100+";";
if (seed==100){
window.clearInterval(id);//傳入setInterval的返回值
fadeBtn.disabled=false;
}
</script>
12、例2:設置一個簡單的時鐘(年+月+日 星期 小時:分鐘:秒)
<p id="clock"></p>
<script type="text/javascript">
setInterval("setClock()",1000);//1秒更新一次
function setClock() {
var date=new Date();
var today=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日";
var timeNow=date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
document.getElementById("clock").innerText=today+" "+"星期"
+date.getDay()+" "+timeNow;
}
</script>