2

I just created a simple JavaScript counter. The first version adds a constant every second to an initial value; the second version adds 1 to the initial value in a proportionately reduced amount of time. I'm not rounding any numbers. But if you let the counter run long enough, the resulting values start diverging considerably. Any idea why that is?

window.onload = function() {
  var Today = new Date();
  var Jan = new Date("January 1 2020 00:00");
  var dif = (Today.getTime() - Jan.getTime()) / 1000;
  const Clklid = 3.55988;
  var new1 = Clklid * dif;
  var new2 = Clklid * dif;
  var text = document.getElementById("text")
  var text2 = document.getElementById("text2")


  setInterval(function() {
    new1 += Clklid;
    // new1 = Math.trunc(new1);
    text.innerHTML = new1 + " g emisí CO2";
  }, 1000);

  setInterval(function() {
    new2 += 1;
    // new2 = Math.trunc(new2);
    text2.innerHTML = new2 + " g emisí CO2";
  }, 1000 / Clklid);
}
<div id="text"></div>
<div id="text2"></div>

https://jsfiddle.net/6t4b1sqk/

j08691
  • 204,283
  • 31
  • 260
  • 272
  • 2
    Note that interval timers use **integer** millisecond counters, and they're not very accurate. – Pointy Apr 05 '20 at 16:43
  • 2
    setTimeout and setInterval are not accurate, use dates instead. Please refer to https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript – ihor.eth Apr 05 '20 at 17:13
  • 1
    Does this answer your question? [How to create an accurate timer in javascript?](https://stackoverflow.com/questions/29971898/how-to-create-an-accurate-timer-in-javascript) – ihor.eth Apr 05 '20 at 17:14

1 Answers1

-1

setInterval is not perfect and actually takes up to 5 milliseconds longer for each iteration. Intervals that update more often will be behind one that update less.

If you want the 2 timers to always show similar values, only use one counter (replace new1 and new2 with new) Alternatively, have both counters update in one function and not in the other:

setInterval(function() {
  new1 += Clklid;
  new2 += 1;
  // new1 = Math.trunc(new1);
  // new2 = Math.trunc(new2);
  text.innerHTML = new1 + " g emisí CO2";
}, 1000);

setInterval(function() {
  // new2 = Math.trunc(new2);
  text2.innerHTML = new2 + " g emisí CO2";
}, 1000 / Clklid);
BlobKat
  • 88
  • 1
  • 8