今天带来的是js中的计时器实现并解决bug,有两种方法解决bug,第一种是自我优化的,第二种是借鉴优化的。
首先来看看怎么实现计时器:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>计时器的实现</title>
</head>
<script type="text/javascript">
var i = 0;//定义从0开始计数
var x;//定义用来保存定时器
function startcount(){//计数的方法
document.getElementById("time").value = i;
i++;
x = setTimeout("startcount()",1000);//不能加var
}
function stopcount(){
clearTimeout(x);
}
</script>
<style type="text/css">
input {
font-size: 20px;
background-color: pink;
}
</style>
<body>
<form action="#" method="post" name="myform">
<input type="text" name="time" id="time" value="" size="40" /><br />
<input type="button" name="start" id="start" value="开始" onclick="startcount()"/>
<input type="button" name="stop" id="stop" value="停止" onclick="stopcount()"/>
</form>
</body>
</html>
现在计时器是实现了,可以我们会发现一个问题,就点击开始计时之后,可以继续点击开始,这样会使得计数变快,这是因为每次调用都叠加了自加。
那怎么解决呢?
第一种方法:通过一个变量来控制按钮的点击次数
如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>从0开始</title>
</head>
<script type="text/javascript">
var i = 0;//定义从0开始计数
var x;//定义用来保存定时器
var isstart = 1;//用来判断是否用户点击了开始
function counttime(){//计数的方法
document.getElementById("time").value = i;
i++;
x = setTimeout("counttime()",1000);//不能加var
}
function startcount() {//当用户点击了开始之后,再次点击开始将无效
if (isstart == 1) {
isstart = 0;
setTimeout("counttime()",1000);
}
}
function stopcount(){
isstart = 1;//当用户点击了停止之后,用户又可以继续点击开始
clearTimeout(x);
}
</script>
<style type="text/css">
input {
font-size: 20px;
background-color: pink;
}
</style>
<body>
<form action="#" method="post" name="myform">
<input type="text" name="time" id="time" value="" size="40" /><br />
<input type="button" name="start" id="start" value="开始" onclick="startcount()"/>
<input type="button" name="stop" id="stop" value="停止" onclick="stopcount()"/>
</form>
</body>
</html>
第二种方法:用户点击按钮之后使按钮不可用
如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<script type="text/javascript">
var i = 0;//定义从0开始计数
var x;//定义用来保存定时器
function startcount(){//计数的方法
document.getElementById("start").disabled = "disabled";
document.getElementById("time").value = i;
document.getElementById("stop").disabled = "";
i++;
x = setTimeout("startcount()",1000);//不能加var
}
function stopcount(){
document.getElementById("start").disabled = "";
document.getElementById("stop").disabled = "disabled";
isstart = 1;//当用户点击了停止之后,用户又可以继续点击开始
clearTimeout(x);
}
</script>
<style type="text/css">
input {
font-size: 20px;
background-color: pink;
}
</style>
<body>
<form action="#" method="post" name="myform">
<input type="text" name="time" id="time" value="" size="40" /><br />
<input type="button" name="start" id="start" value="开始" onclick="startcount()"/>
<input type="button" name="stop" id="stop" value="停止" onclick="stopcount()"/>
</form>
</body>
</html>