hippofish/packages/client/src/scripts/use-interval.ts

29 lines
574 B
TypeScript
Raw Normal View History

2023-01-13 05:40:33 +01:00
import { onMounted, onUnmounted } from "vue";
2023-01-13 05:40:33 +01:00
export function useInterval(
fn: () => void,
interval: number,
options: {
immediate: boolean;
afterMounted: boolean;
},
): void {
2022-07-02 15:07:04 +02:00
if (Number.isNaN(interval)) return;
let intervalId: number | null = null;
if (options.afterMounted) {
onMounted(() => {
if (options.immediate) fn();
intervalId = window.setInterval(fn, interval);
});
} else {
if (options.immediate) fn();
intervalId = window.setInterval(fn, interval);
}
onUnmounted(() => {
if (intervalId) window.clearInterval(intervalId);
});
}