From 105518282fc1df60da9c0638bb4601b235347a37 Mon Sep 17 00:00:00 2001 From: neru Date: Sun, 31 May 2026 11:47:54 -0300 Subject: [PATCH] fix?: only poll presence if tab is visible --- src/app/components/discordstatus.tsx | 41 ++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/src/app/components/discordstatus.tsx b/src/app/components/discordstatus.tsx index 56b546c..430829c 100644 --- a/src/app/components/discordstatus.tsx +++ b/src/app/components/discordstatus.tsx @@ -134,13 +134,14 @@ export function DiscordStatus({ userId }: DiscordStatusParams) { const [loading, setLoading] = useState(true); useEffect(() => { + let interval: NodeJS.Timeout | null = null; + async function fetchRichPresence() { try { const response = await fetch(`https://api.lanyard.rest/v1/users/${userId}`); const json: LanyardResponse = await response.json(); - if (json.success) { + if (json.success) setPresence(json.data); - } } catch (error) { console.error("Failed to fetch Lanyard presence:", error); } finally { @@ -148,9 +149,39 @@ export function DiscordStatus({ userId }: DiscordStatusParams) { } } - fetchRichPresence(); - const interval = setInterval(fetchRichPresence, 30000); - return () => clearInterval(interval); + const startPolling = () => { + if (!interval) { + fetchRichPresence(); + interval = setInterval(fetchRichPresence, 30000); + } + }; + + const stopPolling = () => { + if (interval) { + clearInterval(interval); + interval = null; + } + }; + + const handleVisibilityChange = () => { + if (document.visibilityState === 'visible') + startPolling(); + else + stopPolling(); + + }; + + if (document.visibilityState === 'visible') + startPolling(); + else + setLoading(false); + + document.addEventListener('visibilitychange', handleVisibilityChange); + + return () => { + document.removeEventListener('visibilitychange', handleVisibilityChange); + stopPolling(); + }; }, [userId]); if (loading)