본문 바로가기

javascript

Throttle 과 Debounce

Throttle 과 Debounce

ThrottleDebounce는 이벤트 핸들러가 많은 연산을 수행하는 경우에 대해 제약을 걸어 제어할 수 있는 수준으로 이벤트를 발생시키기 위해 사용 된다.

Throttle은 이벤트를 일정한 주기마다 발생하도록 하며 Debounce는 마지막으로 함수가 호출된 시점에서 특정 시간이 지난 후 한번의 이벤트만 발생하도록 하는 것

위 내용은 구글에 찾아보면 그림으로 친절하게 설명해둔 글이 많으니 참고

const throttleAndDebounce = () => {
  // (1)
  let throttleCheck, debounceCheck;

  return {
    // (2)
    throttle(callback, millisecond) {
      return () => {
        if (!throttleCheck) {
          // (3)
          throttleCheck = setTimeout(() => {
            callback(...arguments);
            throttleCheck = false;
          }, millisecond);
        }
      };
    },

    debounce(callback, millisecond) {
      return () => {
        // (4)
        clearTimeout(debounceCheck);
        debounceCheck = setTimeout(() => {
          callback(...arguments);
        }, millisecond);
      };
    },
  };
};
  1. 쓰로틀링과 디바운스를 체크하기 위한 변수를 만들어준다.
  2. throttle과 debounce 모두 실행할 콜백 함수와 실행할 주기를 인자로 받는다.
  3. setTimeout을 이용하여 설정한 주기마다 콜백이 실행될 수 있도록 하였고, 실행이 끝난 후에는 다시 throttleCheck를 false로 만들어 주어, 설정한 주기마다 이벤트가 한 번씩만 호출되도록 한다.
  4. clearTimeout을 이용하여 이벤트 발생을 무시해주고, 마지막 호출 이후, 일정 시간이 지난 후에 단 한 번만, 이벤트가 호출되도록 한다.

Lodash 의 throttle, debounce

const lodashThrottle = _.throttle(
  () => {
    throttleLodashCount += 1;
    throttleLodashScroll.innerHTML = throttleLodashCount;
  },
  3000,
  { leading: true, trailing: true },
);
const lodashDebounce = _.debounce(
  () => {
    debounceLodashCount += 1;
    debounceLodashScroll.innerHTML = debounceLodashCount;
  },
  3000,
  { leading: false, trailing: true },

lodash의 경우 옵션이 있다.

  • leading - 시간을 시작시 실행
  • trailing - 시간이 끝날때 실행

두 가지 옵션으로 원하는 기능으로 변경할 수 있다. 자세한 내용은 lodash 홈페이지에 자세히 나와있다.

Throttle , Debounce 는 이벤트 요청을 실시간으로 할때 맞춰서 사용한다.