56 lines
1.2 KiB
TypeScript
56 lines
1.2 KiB
TypeScript
import { ref, watch, onUnmounted } from 'vue'
|
|
import type { Ref } from 'vue'
|
|
import { AUTO_REFRESH_INTERVAL_S } from '../data/constants'
|
|
|
|
export function useAutoRefresh(fetchFn: () => Promise<void>, enabled: Ref<boolean>) {
|
|
const countdown = ref(AUTO_REFRESH_INTERVAL_S)
|
|
|
|
let intervalId: ReturnType<typeof setInterval> | null = null
|
|
let tickId: ReturnType<typeof setInterval> | 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 }
|
|
}
|