avatar
Published on

typescript debounce

Author
  • avatar
    Name
    yceffort

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation.

좜처

λ””λ°”μš΄μŠ€λŠ” κ³Όλ‹€ν•œ 이벀트 둜직이 μ‹€ν–‰λ˜λŠ” 것을 λ°©μ§€ν•˜λŠ” ν•¨μˆ˜λ‘œ, 호좜이 λ°˜λ³΅λ˜λŠ” λ™μ•ˆμ—λŠ” λ°˜λ³΅ν•΄μ„œ 둜직이 μ‹€ν–‰λ˜λŠ” 것을 막고, μ„€μ •ν•œ μ‹œκ°„μ΄ μ§€λ‚˜κ³  λ‚˜μ„œμ•Ό 둜직이 μ‹€ν–‰ν•˜κ²Œ ν•˜λŠ” ν•¨μˆ˜λ‹€.

export function debounce<Params extends any[]>(
  func: (...args: Params) => any,
  timeout: number,
): (...args: Params) => void {
  let timer: NodeJS.Timeout
  return (...args: Params) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, timeout)
  }
}

즉, λ°˜λ³΅λ˜λŠ” μ΄λ²€νŠΈκ°€ κ³„μ†ν•΄μ„œ 싀행될 λ•Œ, 맀번 κ·Έ 이벀트λ₯Ό μ‹€ν–‰ν•˜λŠ” 것이 μ•„λ‹ˆλΌ, timeout 만큼의 μ‹œκ°„μ΄ 흐λ₯Έλ’€μ—, μ΄μ „μ˜ 이벀트λ₯Ό λ¬΄μ‹œν•˜κ³  이벀트 ν•˜λ‚˜λ§Œ μ‹€ν–‰ν•˜λŠ” 것이닀.