createTimeSource: reflects to the pagevisibility

This commit is contained in:
thislight 2024-10-28 13:56:50 +08:00
parent d1c073e33e
commit 81bf27df63
No known key found for this signature in database
GPG key ID: A50F9451AC56A63E
3 changed files with 22 additions and 9 deletions

BIN
bun.lockb

Binary file not shown.

View file

@ -36,6 +36,7 @@
"@solid-primitives/i18n": "^2.1.1",
"@solid-primitives/intersection-observer": "^2.1.6",
"@solid-primitives/map": "^0.4.13",
"@solid-primitives/page-visibility": "^2.0.17",
"@solid-primitives/resize-observer": "^2.0.26",
"@solidjs/router": "^0.14.10",
"@suid/icons-material": "^0.8.1",

View file

@ -1,3 +1,4 @@
import { usePageVisibility } from "@solid-primitives/page-visibility";
import {
Accessor,
createContext,
@ -15,19 +16,30 @@ export const TimeSourceProvider = TimeSourceContext.Provider;
export function createTimeSource() {
let id: ReturnType<typeof setTimeout> | undefined;
const [get, set] = createSignal(new Date());
const visible = usePageVisibility();
createRenderEffect(() =>
untrack(() => {
id = setTimeout(() => {
set(new Date());
}, 30 * 1000);
}),
);
onCleanup(() => {
const cancelTimer = () => {
if (typeof id !== "undefined") {
clearInterval(id);
}
id = undefined;
};
const resetTimer = () => {
cancelTimer();
set(new Date());
id = setTimeout(() => {
set(new Date());
}, 30 * 1000); // refresh rate: 30s
};
createRenderEffect(() => {
onCleanup(cancelTimer);
if (visible()) {
resetTimer();
} else {
console.debug("createTimeSource: page is invisible, cancel the timer")
}
});
return get;