import { ref, watch, onUnmounted } from 'vue' import type { Ref } from 'vue' import { AUTO_REFRESH_INTERVAL_S } from '../data/constants' export function useAutoRefresh(fetchFn: () => Promise, enabled: Ref) { const countdown = ref(AUTO_REFRESH_INTERVAL_S) let intervalId: ReturnType | null = null let tickId: ReturnType | null = null function startRefresh() { stopRefresh() countdown.value = AUTO_REFRESH_INTERVAL_S // Countdown tick every second tickId = setInterval(() => { countdown.value = Math.max(0, countdown.value - 1) }, 1000) // Fetch every interval intervalId = setInterval(async () => { await fetchFn() countdown.value = AUTO_REFRESH_INTERVAL_S }, AUTO_REFRESH_INTERVAL_S * 1000) } function stopRefresh() { if (intervalId !== null) { clearInterval(intervalId) intervalId = null } if (tickId !== null) { clearInterval(tickId) tickId = null } } watch( enabled, (val) => { if (val) { startRefresh() } else { stopRefresh() } }, { immediate: true } ) onUnmounted(() => { stopRefresh() }) return { countdown } }