<!-- 定时器案例 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
#clock{
border:1px solid red;
width:200px;
text-align:center;
font-size:20px;
height:30px;
line-height:30px;
}
</style>
<script type="text/javascript">
//开始的方法
var id;
function start(){
//若id非空,则定时器已启动过,就不要再次启动了
if(!id){
id=setInterval(function() {
//获取当前客户端的时间
var d=new Date();
//获取本地格式的时间
var now=d.toLocaleTimeString();
//将时间写入clock
var p=document.getElementById("clock");
p.innerHTML=now;
}, 1000);
}
}
//停止的方法
function stop(){
//id非空时定时器处于启动状态,此时停止它才有效
if(id){
clearInterval(id);
id=null;
}
}
</script>
</head>
<body>
<p>
<input type="button" value="开始" οnclick="start();">
<input type="button" value="停止" οnclick="stop();">
</p>
<p id="clock"></p>
</body>
</html>
<!-- 定时器案例 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
//发送
var id;
function send(){
//若id非空,表示定时器已启动,此时就不要启动了
if(id){
return;
}
//显示正在发送
var p=document.getElementById("msg");
p.innerHTML="正在发送";
//推迟三秒显示已发送
id=setTimeout(function() {
p.innerHTML="已发送";
//为了能再次启动,要清空id
id=null;
}, 3000);
}
//撤销
function cancel(){
//id非空时,表示定时器已启动,此时才能撤销
if(id){
//显示为已撤销
var p=document.getElementById("msg");
p.innerHTML="撤销成功";
//停止定时器
clearTimeout(id);
//为了能再次启动,要清空id
id=null;
}
}
</script>
</head>
<body>
<p>
<input type="button" value="发送" οnclick="send();">
<input type="button" value="撤销" οnclick="cancel();">
</p>
<p id="msg"></p>
</body>
</html>