import { ref, onUnmounted } from 'vue' /** * 自适应间隔轮询:tick 返回后按 getInterval() 调度下一次 * @param {() => Promise|void} tickFn * @param {() => number} getIntervalMs */ export function useLivePoll(tickFn, getIntervalMs = () => 1000) { const lastTickAt = ref(null) const ticking = ref(false) let timer = null let inFlight = false let running = false async function runTick() { if (inFlight) return inFlight = true ticking.value = true try { await tickFn() lastTickAt.value = Date.now() } catch (e) { console.error('[livePoll]', e) } finally { inFlight = false ticking.value = false } } function scheduleNext() { if (!running) return clearTimeout(timer) const ms = Math.max(500, getIntervalMs()) timer = setTimeout(async () => { await runTick() scheduleNext() }, ms) } function start() { if (running) return running = true runTick().then(scheduleNext) } function stop() { running = false clearTimeout(timer) timer = null } function restart() { stop() start() } onUnmounted(stop) return { start, stop, restart, runTick, lastTickAt, ticking } }