Skip to content

Commit

Permalink
feat: add getServerNow to TimeContext (#4047)
Browse files Browse the repository at this point in the history
  • Loading branch information
rosvik authored Nov 20, 2023
1 parent 27c5495 commit 02c7c4f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
14 changes: 13 additions & 1 deletion src/time/TimeContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ type TimeContextState = {

const TimeContext = createContext<TimeContextState | undefined>(undefined);

// The number of milliseconds the device time is ahead of server time.
let serverDiff = 0;

/**
* Returns the current time in milliseconds.
*/
export const getServerNow = () => Date.now() - serverDiff;

export const TimeContextProvider: React.FC = ({children}) => {
const [clockIsRunning, setClockIsRunning] = useState(false);
const [serverNow, setServerNow] = useState(Date.now());
Expand All @@ -26,7 +34,11 @@ export const TimeContextProvider: React.FC = ({children}) => {
}).then(() => setClockIsRunning(true));
}, []);
useInterval(
() => clock.currentTimeMillis().then(setServerNow),
() =>
clock.currentTimeMillis().then((ms) => {
serverDiff = Date.now() - ms;
setServerNow(ms);
}),
2500,
[],
!clockIsRunning,
Expand Down
6 changes: 5 additions & 1 deletion src/time/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
export {TimeContextProvider, useTimeContextState} from './TimeContext';
export {
TimeContextProvider,
useTimeContextState,
getServerNow,
} from './TimeContext';

0 comments on commit 02c7c4f

Please sign in to comment.