43 lines
806 B
TypeScript
43 lines
806 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: 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())
|
||
|
);
|
||
|
}
|