一、定时器概述
开发时用到的js定时器主要分为两种:
1.一次性的定时器setTimeOut方法,通过设置一定的时间,时间到就执行。
var timer=setTimeout(fun,毫秒数);
清除的方法
clearTimeout(timer)
2.周期性的定时器setInterval方法,根据设定的时间周期进行执行代码或者代码块。
var timer=setInterval(fun,毫秒数);
清除的方法
clearInterval(timer)
二、定时器的实现案例
1.setTimeOut案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Timer</title>
</head>
<body>
<p>
这是定时器测试案例
</p>
<script>
<!--/定时器 异步运行-->
function hello() {
alert("hello");
}
//使用方法名字执行方法
var t1 = window.setTimeout(hello, 1000);//直接调用函数不需要带括号,这里是在执行hello的回调函数
var t2 = window.setTimeout("hello()", 3000);//这里是执行函数后得到字符串的返回结果,将字符串的返回结果作为返回结果响应定时器
window.clearTimeout(t1);//去掉定时器
</script>
</body>
</html>
2.setInterval案例
在指定时间为周期循环执行
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Timer</title>
</head>
<body>
<p>
这是定时器测试案例
</p>
<script>
//实时刷新 时间单位为毫秒
setInterval(myFunction,8000);
/* 刷新查询 */
function myFunction(){
alert('每8秒调一次')
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Timer</title>
</head>
<body>
<p>
这是定时器测试案例
</p>
<script>
//实时刷新 时间单位为毫秒
setInterval("myFunction()",8000);//使用字符串执行方法
/* 刷新查询 */
function myFunction(){
alert('每8秒调一次')
}
</script>
</body>
</html>
三、定时器的选择
两种方法根据不同的场景和业务需求择而取之,
对于这两个方法,需要在每隔一个固定的时间间隔后就精确地执行某动作,最好使用setInterval。如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout