当我点击按钮时功能不起作用?
当我单击按钮时,计时器应该显示倒计时器。但按钮不起作用。
let timerCounter = document.getElementById("timer-counter");
let timer;
let timerCount;
function startTimer() {
timer = setInterval(function() {
timerCount--;
timerElement.textContent = "Time; " + timerCount;
if (timerCount === 0) {
clearInterval(timer);
}
});
}
startButton.addEventListener("click", startTimer);
when i click my button, a timer is supposed to display a countdown timer. But the button does not work.
let timerCounter = document.getElementById("timer-counter");
let timer;
let timerCount;
function startTimer() {
timer = setInterval(function() {
timerCount--;
timerElement.textContent = "Time; " + timerCount;
if (timerCount === 0) {
clearInterval(timer);
}
});
}
startButton.addEventListener("click", startTimer);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我到目前为止发现的:
timerCount
,需要指定它的初始值才能工作。timerElement
而不是您声明的timerCounter
。This is what I found so far:
timerCount
, need to specify the initial value for it to work.timerElement
instead oftimerCounter
that you've declared.delay
.这是一种稍微不同的方法,可以避免全局变量的一些问题。侦听器调用的函数初始化计数,然后返回单击按钮时调用的新函数(闭包)。它还使用了
setTimeout
,我发现它更容易理解。Here's a slightly different approach that avoids some of the problems with global variables. The function the listener calls initialises the count, and then returns a new function (a closure) that is called when the button is clicked. It also uses
setTimeout
which I find more easy to understand.我相信这可以改进。
I'm sure this could be improved.