UNPKG

vue-hooks-plus

Version:
43 lines (42 loc) 928 B
import { ref, watchEffect, isRef, unref } from "vue"; function useInterval(fn, delay, options) { const immediate = options == null ? void 0 : options.immediate; const fnRef = ref(fn); const timerRef = ref(null); const setupInterval = () => { if (isRef(delay)) { if (typeof delay.value !== "number" || delay.value < 0) return; } else { if (typeof delay !== "number" || delay < 0) return; } if (immediate) { fnRef.value(); } const _deply = unref(delay); timerRef.value = setInterval(() => { fnRef.value(); }, _deply); }; const clear = () => { if (timerRef.value) { clearInterval(timerRef.value); } }; const restart = () => { clear(); setupInterval(); }; watchEffect((onInvalidate) => { setupInterval(); onInvalidate(clear); }); return { clear, restart }; } export { useInterval as default };