定时器是一个简单的异步机制
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>