jjroley
jjroley

Reputation: 322

Accurate timer in Nodejs

I'm building a live chess app, and I'm trying to add a timer to it. However, I am struggling to find a way to make the timer accurate. I have run some tests, and setInterval and setTimeout are extremely inaccurate, with a ten minute timeout being off by over three minutes. I also tried using setInterval with in interval of 100ms, but even that was off by over minute, when the tab was not active. That was just with the javascript window.setInterval; with nodejs, it hasn't been more than 10ms off, but I'm afraid it will if the server gets busy. I'm hoping to find a way to have the game end within at least a tenth of a second of the real time.

Any suggestions? Thanks!

Upvotes: 0

Views: 930

Answers (1)

indolentdeveloper
indolentdeveloper

Reputation: 1313

an ideal approach would be to use absolute clock time to get time elapsed and timer to have that check.

Something like code below.

const startTime = new Date();

const maxTime = 5 * 1000; // 60 seconds
setInterval(() => {
  checkExpired();
}, 300);

function checkExpired() {
  const curTime = new Date();

  timeDifference = Math.abs(curTime.getTime() - startTime.getTime());

  if (timeDifference > maxTime) {
    console.log("time up");
  }
}

The browser will not run setInterval as required due to performance reason. https://usefulangle.com/post/280/settimeout-setinterval-on-inactive-tab

If you need to run timer with required interval then it can be run in worker thread.

some info here. How can I make setInterval also work when a tab is inactive in Chrome?

But my guess is increased granularity is fine for non active tab.

Upvotes: 1

Related Questions