You wrote a fantastic real-time frontend application using React. Great!
But the system time of the user who is using your application is wrong. Now when your application does Date.now()
or new Date()
, everything will go for a toss.
This is why relying on the user's system time is a bad idea. It's not guaranteed to be correct.
So, what is the solution?
Rely on the server's time.
How?
Make an API call to the server to get the server's time.
const serverTime = getServerTime();
Write a function that will take the server's time as an argument and sync the UI time with it.
function syncWithServerTime(serverTime) {
}
Get the current system time. Calculate the difference between the server time and the system time.
function syncWithServerTime(serverTime) {
const curTime = Date.now();
const diff = curTime - serverTime;
}
Now return a new function that will return the correct time using the difference. We will then use it to get the current time instead of using Date
.
function syncWithServerTime(serverTime) {
const curTime = Date.now();
const diff = curTime - serverTime;
return function() {
return Date.now() - diff;
}
}
Sync the application's time with the server's time as soon as it loads.
const serverTime = getServerTime();
const getCurrentTime = syncWithServerTime(serverTime);
From now on, where ever you want to get the current time use the getCurrentTime
function.
const curTime = getCurrentTime();
Full Code:
window.onload = function() {
const serverTime = getServerTime();
function syncWithServerTime(serverTime) {
const curTime = Date.now();
const diff = curTime - serverTime;
return function() {
return Date.now() - diff;
}
}
const getCurrentTime = syncWithServerTime(serverTime);
// Use getCurrentTime everywhere...
}
Note: Time is represented as the epoch in the example.
It's a simple trick, but a very useful one.
Top comments (1)
Please note that this code won't completely synchronize local and backend time because
getServerTime
will suffer from non-constant http request latency that can not be compensated.The resulting time will have a lag starting from ~40ms and till several seconds depending on network conditions.