使用setInterval和EventListeners为start和rest特性构建javascript计时器.<



我正在做一个定时器项目,有开始复位按钮,这里我附了我的答案,但它不起作用。

这里是script.js,我已经为定时器写了一个startreset功能(按钮)定时器值将坐在h3标签内,类名为.timer

计时器启动但不停止!你能帮我修一下吗?

const btnStr = document.querySelector(".start-btn");
const btnRst = document.querySelector(".reset-btn");
const btnStp = document.querySelector(".stp-btn");
let timer = document.querySelector(".timer");
let dynamic = 0;
let strtIt = () =>
setInterval(function() {
dynamic++;
timer.innerHTML = `${dynamic}`;
}, 1000);
btnStr.addEventListener("click", strtIt);
btnRst.addEventListener("click", () => clearInterval(strtIt));
<div>
Time: <span class="timer"></span>
</div>
<button class="start-btn">Start</button>
<button class="reset-btn">Reset</button>
<button class="stp-btn">Stop</button>

我想你缺少一个变量来存储间隔。正确的实现应该是这样的。点击run code snippet试试。

const btnStr = document.querySelector(".start-btn");
const btnRst = document.querySelector(".reset-btn");
const btnStp = document.querySelector(".stp-btn");
let timer = document.querySelector(".timer");
let dynamic = 0;
let interval = null;
let strtIt = () => {
interval = setInterval(function () {
dynamic++;
timer.innerHTML = `${dynamic}`;
}, 1000);
}
let stopIt = () => {
if (interval) clearInterval(interval)
}

btnStr.addEventListener("click", strtIt);
btnRst.addEventListener("click", stopIt);
<div>
<button class="start-btn">start</button>
<button class="reset-btn">reset</button>
<button class="stop-btn">stop</button>
<div class="timer">timer</div>
</div>

相关内容

  • 没有找到相关文章

最新更新