30 lines
730 B
TypeScript
30 lines
730 B
TypeScript
import {onUnmounted, ref} from "vue";
|
|
|
|
const DEFAULT_INTERVAL = 1_000;
|
|
|
|
export const useAutoRefresh = (callback: () => void | Promise<void>, interval: number = DEFAULT_INTERVAL) => {
|
|
const active = ref(false);
|
|
let timer: ReturnType<typeof setInterval> | undefined;
|
|
|
|
const stop = () => {
|
|
if (timer) {
|
|
clearInterval(timer);
|
|
timer = undefined;
|
|
}
|
|
active.value = false;
|
|
};
|
|
|
|
const start = () => {
|
|
if (active.value) {
|
|
return;
|
|
}
|
|
active.value = true;
|
|
timer = setInterval(callback, interval);
|
|
};
|
|
|
|
const toggle = () => active.value ? stop() : start();
|
|
|
|
onUnmounted(stop);
|
|
|
|
return {active, start, stop, toggle};
|
|
}; |