2022-06-26 03:12:58 +09:00
|
|
|
import { onMounted, onUnmounted } from 'vue';
|
|
|
|
|
|
|
|
export function useInterval(fn: () => void, interval: number, options: {
|
|
|
|
immediate: boolean;
|
|
|
|
afterMounted: boolean;
|
|
|
|
}): void {
|
2022-07-02 22:07:04 +09:00
|
|
|
if (Number.isNaN(interval)) return;
|
|
|
|
|
2022-06-26 03:12:58 +09: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);
|
|
|
|
});
|
|
|
|
}
|