tutu/src/platform/timesrc.ts

43 lines
806 B
TypeScript
Raw Normal View History

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() {
let id: number | undefined;
const [get, set] = createSignal(new Date());
createRenderEffect(() =>
untrack(() => {
id = setTimeout(() => {
set(new Date());
}, 30 * 1000);
}),
);
onCleanup(() => {
if (typeof id !== "undefined") {
clearInterval(id);
}
});
return get;
}
export function useTimeSource() {
return (
useContext(TimeSourceContext) ??
(console.warn("useTimeSource() is used but no source is provided"),
createTimeSource())
);
}