我的 JavaScript 计时器工作得很奇怪:它从 3-2 开始,然后突然结束(没有经过步骤 1 和 0)。这是代码:
var count = 3;
function countDown() {
document.getElementById("count").innerHTML = count;
if (count > 0) {
count--
}
else {
clearInterval(ncount);
document.getElementById("count").style.display = "none"
}
var ncount = setInterval("countDown()", 1000);
}
<form id="askName">
<label> Enter your username: </label>
<input id="input" type="text" required maxlength="10">
<button type="button" onclick="countDown()"> Submit </button>
</form>
<h2 id="count"> </h2>
为什么会出现这种情况?
最佳答案
问题是你的setInterval
正在调用生成另一个 setInterval
的函数,这会导致计数更快地递减。您可以使用内部函数来避免此问题。
var count = 3;
function countDown() {
function helper(){
document.getElementById("count").innerHTML = count;
if (count > 0) {
count--;
} else {
clearInterval(ncount);
document.getElementById("count").style.display = "none"
}
}
var ncount = setInterval(helper, 1000);
}
<form id="askName">
<label> Enter your username: </label>
<input id="input" type="text" required maxlength="10">
<button type="button" onclick="countDown()"> Submit </button>
</form>
<h2 id="count"> </h2>
关于javascript - 我的 JavaScript 倒计时器无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63176225/