yceffort
BACK TO INDEX
◆ ESSAY

typescript debounce

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 만큼의 시간이 흐른뒤에, 이전의 이벤트를 무시하고 이벤트 하나만 실행하는 것이다.

관련 글

  • #browser#web-performance

    주요 렌더링 경로 - 브라우저의 원리를 이해하고 최적화 하기

    [Critical Rendering Path](https://developers.google.com/web/fundamentals/performance/critical-rendering-path?hl=ko)를 요약했습니다. 이글을 보는게 더 나아요 사실 ```toc tight: true, from-heading: 2 to-heading: 3 ``` 성...

    13분
  • ◆ Core Web Vitals 직접 수집하기 · 2편
    #web-performance#debugging#browser

    페이지를 떠나는 순간 핵심 웹 지표를 보내기

    페이지를 떠날 때 CLS와 INP가 누락되는 원인을 OTel JS의 전송 방식과 flush 순서에서 찾기

    수정 32분
  • ◆ coldpath 제작기 · 1편
    #web-performance#bundler#blogging

    블로그의 JavaScript가 언제 실행되는지 추적해보기

    추석맞이 뻘짓 대작전 1탄: 내 블로그 부터 살펴보기

    수정 32분
  • #web-performance

    웹사이트의 성능지표, Core Web Vital

    조만간 웹사이트 하나씩 분석해 보겠습니다

    수정 10분