点击开始按钮,参数变为真,计时器才会改变,有效避免了反复调用setInterval函数,从而有效避免了setInterval()引发的加速效果。
效果截图:
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简易计时器</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
input{
margin-top: 20px;
width: 283px;
height: 40px;
border-radius: 3px;
text-align: center;
font-size: 25px;
line-height: 40px;
}
button{
margin-top: 8px;
width: 90px;
height: 40px;
font-size: 25px;
line-height: 40px;
}
</style>
</head>
<body>
<div><input type="text" id="timer" value="0s"></div>
<button onclick="begin()">开始</button>
<button onclick="stop()">停止</button>
<button onclick="cleartime()">清零</button>
</body>
<script type="text/javascript">
a=0;
index=false;
sobj=setInterval(function(){
if(index){
time=++a;
document.getElementById('timer').value=time+"s";
}
},1000);
//点击开始按钮,index变为真,计时器才会改变,有效避免了反复调用setInterval函数
function begin(){
index=true;
}
function stop(){
index=false;
}
function cleartime(){
index=false;
time=0;
a=0;
document.getElementById('timer').value=time+"s";
return index;
}
</script>
</html>