From 2409fa2b8d5a63c81bac840125da132607ac3d2a Mon Sep 17 00:00:00 2001 From: Max Nuding Date: Wed, 5 Apr 2023 17:10:18 +0200 Subject: [PATCH] Fix #19 --- src/routes/+page.svelte | 60 +++++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 23 deletions(-) diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte index 08a134d..d799b4b 100644 --- a/src/routes/+page.svelte +++ b/src/routes/+page.svelte @@ -8,34 +8,48 @@ import LoadMoreComponent from '$lib/components/LoadMoreComponent.svelte'; export let data: PageData; +const refreshInterval = parseInt(PUBLIC_REFRESH_INTERVAL); let interval: NodeJS.Timer | null = null; let moreOlderPostsAvailable = true; let loadingOlderPosts = false; -onMount(async () => { - interval = setInterval(async () => { - const params = new URLSearchParams(); - if (data.posts.length > 0) { - params.set('since', data.posts[0].created_at); +function refresh() { + const params = new URLSearchParams(); + if (data.posts.length > 0) { + params.set('since', data.posts[0].created_at); + } + fetch(`/api/posts?${params}`) + .then(r => r.json()) + .then((resp: Post[]) => { + if (resp.length > 0) { + // Prepend new posts, filter dupes + // There shouldn't be any duplicates, but better be safe than sorry + const combined = resp.concat(data.posts); + const filteredPosts = combined.filter((obj, index, arr) => { + return arr.map(mapObj => mapObj.url).indexOf(obj.url) === index; + }); + data.posts = filteredPosts; } - await fetch(`/api/posts?${params}`) - .then(r => r.json()) - .then((resp: Post[]) => { - if (resp.length > 0) { - // Prepend new posts, filter dupes - // There shouldn't be any duplicates, but better be safe than sorry - const combined = resp.concat(data.posts); - const filteredPosts = combined.filter((obj, index, arr) => { - return arr.map(mapObj => mapObj.url).indexOf(obj.url) === index; - }); - data.posts = filteredPosts; - } - }) - .catch(e => { - // TODO: Show error in UI - console.error('Error loading newest posts', e); - }); - }, parseInt(PUBLIC_REFRESH_INTERVAL)); + }) + .catch(e => { + // TODO: Show error in UI + console.error('Error loading newest posts', e); + }); +} + +onMount(async () => { + interval = setInterval(refresh, refreshInterval); + + // - If the page is hidden, slow down refresh rate + // - If the page is shown, bump up refresh rate + document.addEventListener('visibilitychange', () => { + const delay = document.hidden ? refreshInterval * 10 : refreshInterval; + if (interval) { + clearInterval(interval); + } + interval = setInterval(refresh, delay); + }); + return () => { if (interval !== null) { clearInterval(interval)