setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。
setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
- 从1 打印到10 每隔一秒打印一次。
// 定时器
var num = 1;
var timer = setInterval(function () {
test.innerHTML = ++num;
if (num == 10) {
//关闭定时器
clearInterval(timer);
}
}, 1000)
- 图片自动切换
<img id="img1" src="img/1.png" alt="">
<div>
<button id="btn01">开始播放</button>
<button id="btn02">结束播放</button>
</div>
var img1 = document.getElementById("img1");
var btn01 = document.getElementById("btn01");
var btn02 = document.getElementById("btn02");
var imgs = ["img/1.png", "img/2.png", "img/3.png", "img/4.png"];
var index = 0;
/*
开启定时器 开启定时器之前为了避免用户多次点击, 可以先关闭定时器再开启
*/
var imgTimer;
btn01.onclick = function () {
clearInterval(imgTimer);
imgTimer = setInterval(function () {
index++;
if (index > imgs.length - 1) {
index = 0;
}
img1.src = imgs[index];
}, 1000);
}
btn02.onclick = function () {
clearInterval(imgTimer);
}
- 键盘上下左右控制div移动时卡顿, 用定时器来解决
var box = document.getElementById("box");
var speed = 10;
var dir = 0;
document.onkeydown = function (e) {
dir=e.keyCode;
}
document.onkeyup=function(e){
dir=0;
}
setInterval(function(){
switch (dir) {
case 37:
box.style.left = box.offsetLeft - speed + "px";
break;
case 38:
box.style.top = box.offsetTop - speed + "px";
break;
case 39:
box.style.left = box.offsetLeft + speed + "px";
break;
case 40:
box.style.top = box.offsetTop + speed + "px";
break;
}
},30)
setTimeout() 延时器, 函数在一段时间之后再执行。
关闭延时器 clearTimeout();
- 页面加载5秒以后,弹出广告框
setTimeout(function(){
alert("广告来了");
},5000)