From f8303382ef3b824c8c644c5509d512d82afc6413 Mon Sep 17 00:00:00 2001 From: Ou Date: Sun, 20 Oct 2024 13:50:19 +0800 Subject: [PATCH] feat(ui): disable relative time sync when window is not visible --- src/hooks/useRelativeTime.ts | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/src/hooks/useRelativeTime.ts b/src/hooks/useRelativeTime.ts index ec5a35b..f33339a 100644 --- a/src/hooks/useRelativeTime.ts +++ b/src/hooks/useRelativeTime.ts @@ -1,9 +1,10 @@ import { relativeTime } from "@shared/utils" import { atom, useAtomValue } from "jotai" import { useEffect, useState } from "react" +import { useMount } from "react-use" /** - * change every minute + * changed every minute */ const timerAtom = atom(0) @@ -14,16 +15,33 @@ timerAtom.onMount = (set) => { return () => clearInterval(timer) } +function useVisibility() { + const [visible, setVisible] = useState(true) + useMount(() => { + const handleVisibilityChange = () => { + setVisible(document.visibilityState === "visible") + } + document.addEventListener("visibilitychange", handleVisibilityChange) + return () => { + document.removeEventListener("visibilitychange", handleVisibilityChange) + } + }) + return visible +} + export function useRelativeTime(timestamp: string | number) { const [time, setTime] = useState() const timer = useAtomValue(timerAtom) + const visible = useVisibility() useEffect(() => { - const t = relativeTime(timestamp) - if (t) { - setTime(t) + if (visible) { + const t = relativeTime(timestamp) + if (t) { + setTime(t) + } } - }, [timestamp, timer]) + }, [timestamp, timer, visible]) return time }