game-village-politics-frontend/app/composables/useServerClock.ts

15 lines
497 B
TypeScript
Raw Permalink Normal View History

/**
* The server's clock: the client clock plus the offset the last server snapshot showed.
* Shared, so the header clock and every countdown agree.
*/
export function useServerClock() {
const offset = useState<number>('clock.offset', () => 0)
const clock = useNow()
const now = computed(() => clock.value + offset.value)
/** Call with a snapshot's `server_time`. */
const sync = (serverTime: string) => (offset.value = Date.parse(serverTime) - Date.now())
return { now, sync }
}