我的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>
为什么会发生这种情况?
发布于 2020-07-30 15:21:52
问题是,您的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>
发布于 2020-07-30 15:57:31
这应该没问题的。我试着改变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, 1020);
}<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>
https://stackoverflow.com/questions/63176225
复制相似问题