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 ๋งŒํผ์˜ ์‹œ๊ฐ„์ด ํ๋ฅธ๋’ค์—, ์ด์ „์˜ ์ด๋ฒคํŠธ๋ฅผ ๋ฌด์‹œํ•˜๊ณ  ์ด๋ฒคํŠธ ํ•˜๋‚˜๋งŒ ์‹คํ–‰ํ•˜๋Š” ๊ฒƒ์ด๋‹ค.