定时器
在 JS 中定时器分成两种 : setTimeout() setInterval()
1. setTimeout() 一次性定时器
只在指定的时间后执行一次
开启一次性定时器 :
var timer = setTimeout(fn,1000); 1000毫秒后执行fn函数
/定时器 异步运行 function hello(){ alert("hello"); } //使用方法名字执行方法 var t1 = window.setTimeout(hello,1000); var t2 = window.setTimeout("hello()",3000);//使用字符串执行方法 window.clearTimeout(t1);//去掉定时器
2 . setInterval() 循环定时器
在指定时间为周期循环执行
开启循环定时器 :
setInterval(fn,1000); 一直在刷新
/实时刷新 时间单位为毫秒 setInterval('refreshQuery()',8000); /* 刷新查询 */ function refreshQuery(){ console.log('每8秒调一次')
注意 : 因为定时器对象没有垃圾处理机制,所以使用计时器的时候,要在某一时刻清除定时器 ,否则内存会炸的.