<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="txt" />
<button onclick="startCount()">开始计数!</button>
<button onclick="stopCount()">停止计数!</button>
<script type="text/javascript">
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c = c + 1;
t = setTimeout(function(){timedCount()}, 1000);
}
function startCount() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
</script>
</body>
</html>
不如把计时器的那个函数绑在按钮上,一旦点击按钮自动开始多次调用。清除定时器也一样,绑在按钮上比较好。希望对你有帮助