tutu/src/platform/timesrc.ts

55 lines
1.2 KiB
TypeScript
Raw Normal View History

import { usePageVisibility } from "@solid-primitives/page-visibility";
2024-07-14 12:28:44 +00:00
import {
Accessor,
createContext,
createRenderEffect,
createSignal,
onCleanup,
untrack,
useContext,
} from "solid-js";
const TimeSourceContext = createContext<Accessor<Date>>();
export const TimeSourceProvider = TimeSourceContext.Provider;
export function createTimeSource() {
2024-07-22 14:04:56 +00:00
let id: ReturnType<typeof setTimeout> | undefined;
2024-07-14 12:28:44 +00:00
const [get, set] = createSignal(new Date());
const visible = usePageVisibility();
2024-07-14 12:28:44 +00:00
const cancelTimer = () => {
2024-07-14 12:28:44 +00:00
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")
}
2024-07-14 12:28:44 +00:00
});
return get;
}
export function useTimeSource() {
return (
useContext(TimeSourceContext) ??
(console.warn("useTimeSource() is used but no source is provided"),
createTimeSource())
);
}