import React from 'react'; import { GestureResponderEvent } from 'react-native'; const globally = { lastEventTime: 0 }; export interface ThrottleOptions { /** * 기본값 : true (500ms 적용) * * @example * - throttle={true} -> 기본값 500ms 적용 * - throttle={false} -> 쓰로틀 적용 안함 * - throttle={{ duration: 0 }} -> 쓰로틀 적용 안함 * - throttle={{ duration: 1000 }} -> 1000ms 적용 * - throttle={{ duration: 1000, globally: true }} -> 1000ms 적용, 전역 쓰로틀 */ throttle?: boolean | { duration: number; globally?: boolean }; } /** * 버튼 onPress 이벤트 쓰로틀링 목적으로 개발된 훅입니다. */ export function useThrottledPressHandler( onPress: (event: GestureResponderEvent) => void, throttleOptions: ThrottleOptions['throttle'] = true, ): (event: GestureResponderEvent) => void { const lastEventTimeRef = React.useRef(0); if (typeof throttleOptions === 'undefined') return onPress; if (typeof throttleOptions === 'boolean' && !throttleOptions) return onPress; if (typeof throttleOptions === 'object' && throttleOptions.duration <= 0) return onPress; const DEFAULT_DURATION_MS = 500; const duration: number = throttleOptions === true ? DEFAULT_DURATION_MS : throttleOptions.duration; const throttleGlobally: boolean = typeof throttleOptions === 'object' && throttleOptions.globally === true; function setLastEventTime(time: number) { if (throttleGlobally) { globally.lastEventTime = time; } else { lastEventTimeRef.current = time; } } return (event: GestureResponderEvent): void => { const now = Date.now(); const lastEventTime: number = throttleGlobally ? globally.lastEventTime : lastEventTimeRef.current; if (now - lastEventTime < duration) return; setLastEventTime(now); onPress(event); }; }