Reputation: 31
How can I create a Node.JS accurate timer? I am trying to make a chess website where you can play against other players on time. I am currently using setInterval() and am not sure how accurate that is. I also need some extra accurate timer for the server that should be able to check in a 100th of a second precision can tell if the move is in time and when the game has ended.
Thanks in advance
Upvotes: 2
Views: 1849
Reputation: 108839
For ordinary time-of-day, Date.now()
gives you the date and time in milliseconds as a Javascript number. It has millisecond resolution. Its precision depends on your underlying operating system, but is typically between 10 and 50 milliseconds.
You can use process.hrtime.bigint()
, described here, to retrieve the number of nanoseconds elapsed in nanoseconds.
Like this:
const then = process.hrtime.bigint()
/* do something you want to measure */
const now = process.hrtime.bigint()
const elapsedTimeInSeconds = (now-then) / 1_000_000_000
But be aware of this. Date.now()
gives you a number of milliseconds since the UNIX epoch so it can be used to represent calendar dates and clock times. process.hrtime.bigint()
gives you the number of nanoseconds since some arbitrary start time in the recent past. So it's only really useful for measuring elapsed times within nodejs processes.
And, I'm sure you're aware of single threading in Javascript, so elapsed time doesn't equal CPU time unless you don't do any sort of await
operation in the code you're measuring.
You could also try to use `process.cpuUsage(), described here. Something like this.
const then = process.cpuUsage()
/* do something you want to measure */
const now = process.cpuUsage(then)
const userTimeInSeconds = (now.user - then.user) / 1_000_000
const systemTimeInSeconds = (now.system - then.system) / 1_000_000
Explaining the difference between user and system CPU time is beyond the scope of a Stack Overflow answer, but you can read about it.
Upvotes: 3