Files
creator/frontend/src/composables/usePolling.js
2026-06-12 08:12:11 +02:00

45 lines
949 B
JavaScript

import { onUnmounted } from 'vue'
// Polling mit Visibility-Pause: Tab unsichtbar → stoppen; wieder sichtbar →
// sofortiger Tick, dann weiter, falls isActive(). Stoppt selbst, sobald
// isActive() nach einem Tick false liefert.
export function usePolling(tick, isActive, interval = 3000) {
let timer = null
function stop() {
if (timer) {
clearInterval(timer)
timer = null
}
}
function start() {
stop()
timer = setInterval(async () => {
await tick()
if (!isActive()) stop()
}, interval)
}
function running() {
return !!timer
}
async function onVisibility() {
if (document.hidden) {
stop()
} else {
await tick()
if (isActive()) start()
}
}
document.addEventListener('visibilitychange', onVisibility)
onUnmounted(() => {
stop()
document.removeEventListener('visibilitychange', onVisibility)
})
return { start, stop, running }
}