<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test定时器</title>
</head>
<body>
<input type="button" value= "计时" />
<input type="button" value= "关闭" />
<input type="button" value="0" />
</body>
</html>
<script>
var aInput = document.getElementsByTagName('input');
/*
var timer =null;
aInput[0].onclick=function(){
console.log('关闭');
timer= setInterval(numFun,1000)
}
aInput[1].onclick = function(){
console.log('关闭');
clearInterval(timer)
}
var num =0;
function numFun(){
num++;
console.log(num)
aInput[2].value = num;
}
*/
// 用setTimeout模拟setInterval的功能
var timer2 =null;
var timerFlag =false;
function goTimer(){
// debugger;
if(!timerFlag){
return;
}
numFun();
setTimeout(goTimer,1000)
}
var num =0;
function numFun(){
num++;
// console.log(num)
aInput[2].value = num;
}
aInput[0].onclick=function(){
console.log('开启');
timerFlag = true;
goTimer()
}
aInput[1].onclick=function(){
timerFlag =false;
console.log('关闭');
}
</script>
原文:https://www.cnblogs.com/hyx626/p/10515688.html