Init
This commit is contained in:
35
resources/js/composables/usePolling.js
Normal file
35
resources/js/composables/usePolling.js
Normal file
@@ -0,0 +1,35 @@
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user