36 lines
866 B
JavaScript
36 lines
866 B
JavaScript
import { onUnmounted, ref } from 'vue';
|
|
|
|
export function usePolling(callback, intervalMs = 2000) {
|
|
const isPolling = ref(false);
|
|
let timer = null;
|
|
let consecutiveErrors = 0;
|
|
|
|
function start() {
|
|
if (timer) stop();
|
|
isPolling.value = true;
|
|
consecutiveErrors = 0;
|
|
timer = setInterval(async () => {
|
|
try {
|
|
const shouldStop = await callback();
|
|
consecutiveErrors = 0;
|
|
if (shouldStop) stop();
|
|
} catch {
|
|
consecutiveErrors++;
|
|
if (consecutiveErrors >= 3) stop();
|
|
}
|
|
}, intervalMs);
|
|
}
|
|
|
|
function stop() {
|
|
if (timer) {
|
|
clearInterval(timer);
|
|
timer = null;
|
|
}
|
|
isPolling.value = false;
|
|
}
|
|
|
|
onUnmounted(stop);
|
|
|
|
return { isPolling, start, stop };
|
|
}
|