如何使用 javascript 制作每秒添加特定数字的计数器?

How to make a counter that adds a specific number per second using javascript?

我有以下代码,应该每秒加 2.6。但是在第一次添加之后我得到了 8。 我怎样才能解决这个问题?在此处的测试仪上它可以工作,但在我的页面上我得到 8 https://260044-5.web1.fh-htwchur.ch/

提前致谢。

setTimeout(start, 0000);
var i = 2.6;
var num = document.getElementById('humans');

function start() {
  setInterval(increase, 1000);
}

function increase() {
    if (i < 100000000) {
      i += 2.6;
      num.innerText = Math.round(i);
    }
}
<div id="humans">2.6</div>
<p>Menschen wurden geboren.</p>

您在设置文本时将值四舍五入:

num.innerText = Math.round(i);

如果要显示小数点后第 n 位的值,只需使用 toFixed。 示例:

num.innerText = i.toFixed(1); /* will give you one number after the decimal point */

此处的代码有效,但在您发布的 link 中,您的脚本中有:

//funtion for humans born

setTimeout(start, 0000);
var i = 2.6;
var num = document.getElementById('humans');

function start() {
  setInterval(increase, 1000);
}

function increase() {
    if (i < 100000000) {
      i += 2.6;
      num.innerText = Math.round(i);
    }
}

//funtion for trees cut

setTimeout(start, 0000);
var t = 475.646879756;
var t = document.getElementById('trees');

function startTwo() {
  setInterval(increase, 1000);
}

您正在执行 start 两次:一次在 "humans born" 之后,另一次在 "trees cut" 之后。

因此,您有两个并发间隔,每秒执行两次 increase,并且每个 increase 调用都在操作相同的变量。这就是为什么你立即得到 8。

我不确定你的目标是什么,但是你有不同的变量/函数来为 "humans born" 和 "trees cut" 每秒增加,或者你有一个 start 调用(因此每秒调用一个 increase 函数)。

无论如何,这是你的错误:如果你想理清你的逻辑;我/我们可以进一步提供帮助。

你可以试试这个。主要问题是你的四舍五入,你基本上使用 Math.round() 但你正在处理浮点数据类型。因此,只需使用 YourNumber.toFixed(n),其中 n 是您要显示的小数位数。您可以在下面查看。我只是让您的代码更简短,但您基本上可以更改代码的四舍五入,它应该可以工作..

setTimeout((function(){
  var i = 2.6;
  return function start() {
    setInterval(()=> {
      if (i < 100000000){
        i += 2.6;
        document.getElementById('humans').innerText = i.toFixed(1);
      }
    }, 1000);
  };
})(), 0000);
<div id="humans">2.6</div>
<p>Menschen wurden geboren.</p>