gpt4 book ai didi

javascript - 我怎样才能在我的计数中显示正确的数字

转载 作者:行者123 更新时间:2023-11-30 20:09:33 24 4
gpt4 key购买 nike

我想倒数一个计数器。但是,它总是在一个数字之后开始。我知道问题所在,但找不到解决方案。

function countStart() {
const countdown = setInterval(() => {
time -= 1;
document.getElementById('counter').textContent = time;
if (time < 1) {
clearInterval(countdown);
}
}, 1000);
}

如果我从 10 开始倒数。如果从 9 开始,我该如何更改?

最佳答案

您在显示之前减少了“时间”变量。因此,如果您的“time”变量最初的值为 10,由于在将其设置为元素的 textContent(并因此显示它)之前发生语句“time -=1”,它会在显示之前减少到 9。

在将它设置为计数器元素的 textContent 后,尝试减少您的“时间”变量。

function countStart() {
const countdown = setInterval(() => {
document.getElementById('counter').textContent = time;
time -= 1;
if (time < 1) {
clearInterval(countdown);
}
}, 1000);
}

关于javascript - 我怎样才能在我的计数中显示正确的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52544493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com