TIL High Resolution Time
POSTED ON:
TAGS: gamedev javascript
I was reading about Javascript game design.
The Date object is no longer the recognized method for timing events because it is very imprecise and can be modified by the system clock.
TThe High Resolution Time
API provides the current time in sub-millisecond resolution, more suitable for accurate timing than the Date functionality.It counts the number of milliseconds since navigationStart (when the previous document is unloaded).
With a good High Resolution Time implementation in setTimeout and setInterval, you can provide sub-millisecond accuracy to create a solid 60FPS framerate.
You may have also heard about the Performance API, or performance.now()?
It is a Performance API method that returns a
DOMHighResTimeStamp
(which stands for “High Resolution Time Stamp”), which, in simple words, is a time value in milliseconds in the fractional part between two points in time.
The most common use case for performance.now() is monitoring the time in which a piece of code is executed. Real life use cases could include benchmarking and monitoring performance of video, audio, games and other media.
We talked about the Date Object. Why can't it serve this need?
The biggest difference between
performance.now()
andDate.now()
is thatDate.now()
returns a timestamp in relation to the Unix time (time passed from 00:00:00 UTC, 1 January 1970). This is where we potentially face an issue. How does JavaScript know how much time has elapsed since this date? It gets it from the system clock. But since the system clock lives in our machine, it can be adjusted manually or programmatically, therefore, time precision cannot be guaranteed.
via An Introduction to performance.now()
So how exactly do we use it?
const relativeTimestamp = performance.now();
const absoluteTimestamp = performance.timeOrigin + relativeTimestamp;
console.log(relativeTimestamp);
// 244.43500000052154
console.log(absoluteTimestamp);
// 1561926208892.4001
References:
w3 High Resolution Time
MDN Performance
Related TILs
Tagged: gamedev