JavaScript中的定时器分为两种:setInterval()和 setTimeout()
它们两个都是window上的方法,内部函数中的this指向window
setInterval():循环计时器
举个例子
在html中:
div style="width:100px; height:100px; background-color:red;
position: absolute;left:0;top: 0"></div>
设置一个宽为100px,高为100px的红色小方块,给它一个绝对定位
现在我们让这个方块加速运动,就可以用到setInterval()
在js中:
var div = document.getElementsByTagName('div')[0];
var speed = 2
var timer = setInterval(function(){
speed += speed/7;
div.style.left = parseInt(div.style.left) + speed+ 'px';
div.style.top = parseInt(div.style.top) + speed + 'px';
},200);
方块以每间隔200毫秒加速移动,如果想让方块加速到一定位置,停下来,这时候就要用到清除运动的事件clearInterval();
var div = document.getElementsByTagName('div')[0];
var speed = 2
var timer = setInterval(function(){
speed += speed/7;
div.style.left = parseInt(div.style.left) + speed+ 'px';
div.style.top = parseInt(div.style.top) + speed + 'px';
if(parseInt(div.style.top) > 200 && parseInt(div.style.left) > 200){
clearInterval(timer);
}
},200);
setTimeout:推迟执行,并且只执行事件一次
举个例子:
var timer = setTimeout(function(){
console.log('a');
},1000);
a会延迟1000毫秒才会在控制台上打印出来;
如果想不打印a,就要用到clearTimeout();
var timer = setTimeout(function(){
console.log('a');
},1000);
clearTimeout(timer);
这样a就不会再打印在控制台上。