js延时器setTimeout改造为定时器
核心思维----利用回调函数改造,让setTimeout延时器执行自身回调函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定时器</title>
</head>
<body>
<input type="button" value="开始计时" id="btn">
<input type="text" id="txt" value="0">
<input type="button" value="停止计时" id="btn2">
<script>
//获取元素
var btn = document.getElementById('btn');
var btn2 = document.getElementById('btn2');
var txt = document.getElementById('txt');
//注册事件
//开始计时
btn.onclick = timedCount;
//停止计时
btn2.onclick = function () {
clearTimeout(timer);
btn.disabled = false;
}
var c = 0;
var timer;
function timedCount() {
btn.disabled = true;
txt.value = c;
c += 1;
//延时1s执行程序,执行自身函数timedCount
timer = setTimeout(timedCount, 1000);
}
</script>
</body>
</html>