diff --git a/src/useScroll.ts b/src/useScroll.ts index 0f01b98..224c6dc 100644 --- a/src/useScroll.ts +++ b/src/useScroll.ts @@ -1,21 +1,21 @@ import { DeepReadonly, readonly, ref, Ref } from 'vue' import { useEvent } from './useEvent' +import { throttle } from 'throttle-debounce' export type IScrollResult = [DeepReadonly>, DeepReadonly>, () => void] -export function useScroll(target: string | Element | Ref): IScrollResult { +export function useScroll(target: string | Element | Ref, delay = 200): IScrollResult { const x = ref(0) const y = ref(0) - const [eventTarget, clear] = useEvent( - 'scroll', - () => { - if (eventTarget.value) { - x.value = ((eventTarget.value as unknown) as Element).scrollLeft - y.value = ((eventTarget.value as unknown) as Element).scrollTop - } - }, - { capture: false, passive: true }, - target - ) + let cb = () => { + if (eventTarget.value) { + x.value = ((eventTarget.value as unknown) as Element).scrollLeft + y.value = ((eventTarget.value as unknown) as Element).scrollTop + } + } + if (delay) { + cb = throttle(delay, cb) + } + const [eventTarget, clear] = useEvent('scroll', cb, { capture: false, passive: true }, target) return [readonly(x), readonly(y), clear] }