auto refresh
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
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};
|
||||
};
|
||||
Reference in New Issue
Block a user