Infinite counter with increment at two decimals

[亡魂溺海] 提交于 2021-01-29 12:21:02

问题


Trying to create an infinite counter that starts at 10.41 and increases by 10.41 every second. Have looked at various tutorials but I cannot find one that will account for the increase with a decimal number unit (10.41) every second. This is the code I am using:

setTimeout(start, 0);

var i = 100;
var num = document.getElementById('number');

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

function increase() {
    if (i < 100000) {
      i++;
      num.innerText = i;
    }
}

回答1:


If I understand correctly, all you need to do is, instead of i++ you need to use i += 10.41. I have also changed the initial i value to zero because you want it to start from 10.41 and timer to 1000 instead of 100:

setTimeout(start, 0);

var i = 0;
var num = document.getElementById('number');

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

function increase() {
  if (i < 100000) {
    i += 10.41;
    num.innerText = i.toFixed(2);
  }
}
<span id="number"></span>

Also, I truncated it off to two decimal places using i.toFixed(2);.




回答2:


I would do like:

function Incro(increment, interval, execFunc){
  let iv;
  this.increment = increment; this.interval = interval; this.execFunc = execFunc; this.sum = 0;
  this.start = ()=>{
    iv = setInterval(()=>{
      this.sum += this.increment; this.execFunc();
    }, this.interval);
    return this;
  }
  this.stop = ()=>{
    clearInterval(iv); iv = undefined;
  }
}
const incro = new Incro(10.41, 1000, function(){
  console.clear(); console.log(this.sum.toFixed(2));
  if(this.sum > 100)this.stop();
});
console.log('0.00');
incro.start();
setTimeout(()=>{
  incro.stop();
  setTimeout(()=>{
    incro.start();
  }, 2000);
}, 5150);

As you can see JavaScript time is not exact.



来源:https://stackoverflow.com/questions/64689086/infinite-counter-with-increment-at-two-decimals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!