定时器有两个方法:
setInterval(函数,时间),这个方法保证定时器会不断的被执行,因此需要使用clearInterval(serInterval(函数,时间))进行停止;
setTimeout(函数,时间);这个方法只执行一次
setInterval()的使用:(换背景图片)
<script>
window.onload=function(){
//定义背景图片地址;
var url=['1.jpg','2.jpg','3.jpg','4.jpg'];
//定义计时器;
var timer=null;
//定义变量,传递button值
var btn1=document.getElementById("btn1");
var btn2=document.getElementById("btn2");
//定义一个变量,在变换图片时使用
var num=0;
//触发换背景事件
btn1.onclick=function (){
//先关闭定时器;
clearInterval(timer);
//调用定时器函数
timer=setInterval(function(){
//给整个窗口更换背景图片
document.body.style.background='url('+url[num]+')';
num++;
num%=url.length;
//换图片时间为1s
},1000);
};
//触发停事件
btn2.onclick=function(){
//关闭定时器
clearInterval(timer);
};
};
</script>
<body>
<input type="button" id="btn1" value="换背景吧"/>
<input type="button" id="btn2" value="停"/>
</body>
setTimeout()的使用:(弹出广告)
<style>
//设置browsertext,advert的样式
#browsertext{background:#900;height:400px;width:200px;}
#advert{background:#6F0;height:180px;width:240px;position:absolute;top:10px;left:220px;display:none}
</style>
<script>
window.onload=function(){
//定义变量
var browsertext=document.getElementById("browsertext");
var advert=document.getElementById("advert");
var timer=null;
//鼠标移入,show方法
browsertext.onmouseover=show;
//鼠标移出,hide方法
browsertext.onmouseout=hide;
advert.onmouseover=show;
advert.onmouseout=hide;
function show(){
//show方法执行setTimeout
//关闭定时器;
clearInterval(timer);
//执行setTimeout方法;
setTimeout(function(){
//1s后显示广告
advert.style.display='inline-block';
},1000);
};
//执行hide方法
function hide(){
timer=setTimeout(function(){
//1s后隐藏广告
advert.style.display='none';
},1000);
};
};
</script>
<body>
//打开某个的浏览器界面
<div id="browsertext"></div>
//广告
<div id="advert"></div>
</body>
在使用定时器时,应该要特别注意,要先关掉定时器后在打开,不然会同时打开多个定时器。