tutu/src/platform/timesrc.ts
2024-07-22 22:04:56 +08:00

43 lines
829 B
TypeScript

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: ReturnType<typeof setTimeout> | 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())
);
}