2023-01-12 21:40:33 -07:00
|
|
|
import { onMounted, onUnmounted } from "vue";
|
2022-06-25 12:12:58 -06:00
|
|
|
|
2023-01-12 21:40:33 -07:00
|
|
|
export function useInterval(
|
|
|
|
fn: () => void,
|
|
|
|
interval: number,
|
|
|
|
options: {
|
|
|
|
immediate: boolean;
|
|
|
|
afterMounted: boolean;
|
|
|
|
},
|
|
|
|
): void {
|
2022-07-02 07:07:04 -06:00
|
|
|
if (Number.isNaN(interval)) return;
|
|
|
|
|
2022-06-25 12:12:58 -06:00
|
|
|
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);
|
|
|
|
});
|
|
|
|
}
|