JavaScript 计时事件
通过js,我们可以设置每隔一段时间,执行一次函数,或者延迟一段时间,执行函数
定时器
-
setInterval()
- 功能:每隔参数2的时间,执行一次参数1的函数;
- 参数:参数1:函数 参数2:毫秒数
- 返回值:返回一个数值,用来清除当前计时器
- 语法
setInterval(function(){
函数体
},间隔毫秒数据);
-
clearInterval()
- 功能:用于停止 setInterval() 方法执行的函数代码。
- 参数:setInterval()的返回值
-
运用计时器,在页面上显示时钟:
<body>
<p>页面上显示时钟:</p>
<p id="demo"></p>
<button onclick="myStopFunction()">停止</button>
<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer(){
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction(){
clearInterval(myVar);
}
</script>
延时器
-
setTimeout()
- 功能:延迟参数2的时间,执行一次参数1的函数;
- 参数:参数1:函数 参数2:毫秒数
- 返回值:返回一个数值,用来清除当前计时器
- 语法
setTimeout(function(){
函数体
},间隔毫秒数据);
-
clearTimeout()
- 功能:用于停止 setTimeout(() 方法执行的函数代码。
- 参数:setTimeout(()的返回值
//页面延迟一秒,弹出hello world
var t=setTimeout(function(){
alert("hello world")
},1000)
//停止延时器
clearTimeout(t)