1

I have the following example code:

let last = Date.now()

setInterval(() => {
  console.log(Date.now() - last)
  last = Date.now();

}, 20);

And it gives me the output

node .\fps_tester.js 
20 
26 
29 
31 
31 
31 
30 
30 
29

This is the only code running in this file, and my CPU load is low (around 9%). I tried to write a getaround like so:

let setIntervalPrecise = (callback, interval) => {
  let last_execution = Date.now();

  setInterval(() => {
    let now = Date.now();
    let delta = now - last_execution;
    console.log("Delta: " + delta)
    if (delta >= interval) {
      callback(delta);
      last_execution = now;
    }

  }, 1);
}

But it gives me this nonsense:

node .\fps_tester.js 
Delta: 0
Delta: 15
Delta: 16
Delta: 31
31
...

I also tried with setTimeout, and it gave the same result. I am aware that this code runs just fine on a lot of other systems, but I'm curious as to why it might be failing on mine, and what workarounds I might employ to fix it

System specs:

Windows 10
node v16.14.2
Processor: 11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz   2.30 GHz
RAM: 16.0 GB (15.7 GB usable)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Zock77
  • 951
  • 8
  • 26
  • 1
    You can find interesting content about it [here - How is setTimeout implemented in node.js](https://stackoverflow.com/questions/13616102/how-is-settimeout-implemented-in-node-js) – Wandrille May 11 '23 at 15:18
  • 2
    Because Windows: https://social.msdn.microsoft.com/Forums/en-US/3c4ecabc-60ec-4bd8-9f7e-4a0f81cde8f6/sleep-and-settimer-has-1516-ms-minimum https://stackoverflow.com/questions/3744032/why-are-net-timers-limited-to-15-ms-resolution https://stackoverflow.com/questions/50023261/java-clock-accuracy-on-windows-15-16ms – Bergi May 11 '23 at 15:29

0 Answers0