<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button>别说了</button>
<button>继续说</button>
<span>10</span>
<script>
// 需求: 点检单机按钮 停止, 单机另外一个按钮 继续
let timeId;
let count = 6;
let span = document.querySelector("span");
let stop = document.querySelector("button:nth-of-type(1)");
let go = document.querySelector("button:nth-of-type(2)");
function startTimer() {
// 以后开启定时器之前, 不管之前有没有开启过定事器, 都先清除
clearInterval(timeId);
// 开启定时器
timeId = setInterval(function () {
count--;
span.innerText = count;
if (count == 0) {
count = 6;
// 停止定时器
clearInterval(timeId);
}
}, 1000);
}
// 函数需要手动调用
startTimer();
go.addEventListener("click", function () {
// 开启定时器
startTimer();
});
// addEventListener事件监听
stop.addEventListener("click", function () {
clearInterval(timeId); //清除定时器
});
</script>
</body>
</html>
|