运动
标签(空格分隔): 运动
定时器分为两种
- 重复型定时器: 以指定的时间间隔,做同一件事,只要不停止,一直做下去。
- 延迟型定时器: 在指定的时间间隔后,做一件事,只做一次。
重复型定时器 setInterval
- setInterval(fn, delay, arg1, arg2…)
- fn: 要做的事情
- delay: 时间间隔(单位:ms) 1s === 1000ms
- arg1, arg2…: 如果fn有参数,那么这些代表fn的参数
- 返回值:当前定时器的编号(不同的浏览器这个编号是不一样的)
- html5的最新规范,规定了定时器最短的时间间隔是4ms
setInterval(function() {
console.log(1);
}, 1000);
function fn(n){
// console.log(n);
}
var t1 = setInterval(fn, 1000, 1);
var t2 = setInterval('fn(1)', 1000);
var t3 = setInterval('fn(1)', 1000);
var t4 = setInterval('fn(1)', 1000);
console.log(t1, t2, t3, t4); //t1, t2, t3, t4 代表的是定时器的编号
延迟型定时器
- setTimeout(fn, delay, arg1, arg2…)
- 参数和setInterval是一样的返回值也是当前这个定时器的编号
// function fn(){
// alert('hello!');
// }
//
// setTimeout(fn, 3000);
// -------------------------------------------
(function fn(){
console.log('xxxx');
console.log(setTimeout(fn, 1000));
})();
清除定时器
- clearInterval(要清除的定时器的编号)
- clearTimeout(要清除的定时器的编号)
这2个方法的参数,无论你给它们什么样的数据类型,都不会报错。
// var n = 1;
// var t1 = setInterval(function() {
// console.log(n++);
//
// if(n > 50){
// // clearInterval(t1);
// clearTimeout(t1);
// }
// }, 50);
// var t2 = setTimeout(function() {
// alert('hello')
// }, 3000);
//
// document.onclick = function (){
// clearTimeout(t2);
// };
// -----------------------------
// clearTimeout(null);
// clearTimeout(undefined);
// clearTimeout(function(){});
案例 0926 实例