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

标签 javascript math

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

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/

相关文章:

language-agnostic - 对于 IEEE-754,0 < ABS(const) < 1,(x/const) * const 是否保证为 X 的不同值返回不同的结果?

algorithm - 汽车停在无限的街道上 : find car and compute the complexity

javascript - onclick 单选按钮将数字添加到总数中,但无限添加

Firefox 插件中的 Javascript : Delay in for loop

PHP:检查点/坐标是否在椭圆内部

math - 椭圆的标准形式

algorithm - 使用增量、循环、赋值、零进行除法运算

javascript - AngularJS 工作一次然后不再渲染

javascript - 如何使用jsoup在android中用js解析网页内容

javascript - 带破折号分隔符的 RegEX 14 位数字验证