Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!