效果:
点击开始在控制台输出一句话,点击结束,则停止
代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>本地定时器</title>
<style type="text/css">
*{
}
#b1,#b2{
width: 100px;
height: 30px;
margin-left: 30px;
}
</style>
</head>
<body>
<div>
<input type="button" value="开始" id="b1"/>
<input type="button" value="结束" id="b2"/>
</div>
<script type="text/javascript">
var timer=null;//定时器
var EeleB1=document.getElementById("b1");
var EeleB2=document.getElementById("b2");
EeleB1.onclick=function(){
if(timer==null){
timer=setInterval(function(){
console.log("我真聪明");
})
}
}
EeleB2.onclick=function(){
clearInterval(timer);
timer=null;
}
</script>
</body>
</html>