JS中一次性定时器的使用练习
案例思路:
消息发送的演示案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>消息发送</title>
<style type="text/css">
p {
border:1px solid red;
width:200px;
height:40px;
line-height:40px;
text-align:center;
font-size:20px;
}
</style>
<script type="text/javascript">
var id = null;
function send() {
//正在发送
var p = document.getElementById("msg");
p.innerHTML = "正在发送...";
//推迟2s,发送成功
id = setTimeout(function(){
p.innerHTML = "发送成功";
id = null;
},2000);
}
function cancel() {
//若id非空,则处于正在发送的过程中
if(id){
clearTimeout(id);
var p = document.getElementById("msg");
p.innerHTML = "已取消";
}
}
</script>
</head>
<body>
<input type="button" value="发送"
οnclick="send();">
<input type="button" value="取消"
οnclick="cancel();">
<p id="msg"></p>
</body>
</html>
最终页面显示效果:
点击发送:
2s后显示效果:
若2s内点击取消则显示: