카테고리 없음

throttle 함수 구현하기 (in Typescript)

곽빵 2023. 9. 10. 12:59

개요

throttling 해야하는데 라이브러리를 쓰기 보다는 실제로 구현해 보고 싶었다.

 

코드

function throttle<T extends (...args: any[]) => any, U>(func: T, limit: number): (...funcArgs: Parameters<T>) => void {
  let inThrottle = false;

  return function (this: U, ...args: Parameters<T>) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}
  • inTrottle -> javascript의 클로저를 이용해 전역변수와 같은 역할을 시킨다.
  • <T extends (...args: any[]) => any, U> -> throttle할 함수 T와 this의 타입 U를 제네릭으로 선언
  • (func: T, limit: number) -> throttle 함수의 첫번째 인자로 throttling할 함수를 받고 throttling 시간을 설정
  • : (...funcArgs: Parameters<T>) => void -> throttle 함수의 리턴 타입
  • return function (this: U, ...args: Parameters<T>)  -> 위의 throttle 함수의 리턴 타입과 일치하지 않는 것 처럼 보이지만, this 매개변수는 일반 매개변수와는 다르다. 함수의 매개변수 목록에서 this 매개변수는 런타임에 실제로 전달되는 매개변수로 계산되지 않는다. this 매개변수는 TypeScript this 타입을 알려주는 것으로 사용된다. (매개변수에서도 this는 예약어 같은 느낌으로 사용된다)
  • func.apply(this, args); -> 콜백함수에 같은 컨텍스트를 유지하기 위해서 apply로 this를 맵핑해준다.