定时器
一次性定时器:var dingshiqione = window.setTimeout("js代码","时间t")
执行:是在t之后执行js代码【只会执行一次】
时间:以毫秒为单位
反复性定时器:var dingshiqiduo = window.setInterval("js代码","时间t")
执行:是在t之后执行js代码【执行n多次】
时间:以毫秒为单位
清除定时器:
1.清除一次性定时器:window.clearTimeout(dingshiqione );
2.清除反复性定时器:window.clearInterval(dingshiqiduo );
需要将定时器的名字作为参数传入;
注意:要想清除定时器,一定要给定时器定义名字,匿名定时器无法清除。定时器实例:
网页版时钟:
源码:
<style type="text/css">
div{
border: 10px solid blue;
background: yellow;
height: 100px;
font-size: 30px;
text-align: center;
}
</style>
<script type="text/javascript">
window.onload = init;
function init(){
fn();//启动网网页到时钟一秒事件间隔,直接调用一次可以再刷新网页时直接显示当前时间
window.setInterval("fn()",1000);
}
function fn(){
var n = new Date();
var obj = document.getElementById("timer")
obj.innerHTML = n.toLocaleString();
}
</script>
<body>
<div id="timer">
时间
</div>
</body>
效果: