mason
mason-log.

mason

mason.

안녕하세요. mason 입니다.

javascript

Debounce와 Throttle.

고빈도 이벤트(scroll, resize, input)를 제어하는 Debounce, Throttle 차이와 구현.

  • Debounce: 이벤트가 멈춘 뒤 한 번 실행 (검색 input)
  • Throttle: 일정 간격마다 최대 한 번 실행 (scroll, resize)

⚖️ 비교

디바운스와 스로틀 실행 타이밍 비교

DebounceThrottle
실행 시점마지막 호출 후 delay 경과delay 간격마다
연속 호출이전 타이머 취소, 재예약간격 내 호출 무시 또는 trailing
대표 UX타이핑 끝나면 API 검색스크롤 중 100ms마다 위치 체크

💻 간단 구현

function debounce(fn, delay) {
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), delay);
  };
}

function throttle(fn, delay) {
  let last = 0;
  return (...args) => {
    const now = Date.now();
    if (now - last >= delay) {
      last = now;
      fn(...args);
    }
  };
}
  • React: useMemo로 debounced 함수를 만들거나 lodash debounce + cleanup에서 cancel()
  • leading vs trailing: 첫 호출 즉시 vs 마지막 호출 후 — UX에 맞게 선택
  • requestAnimationFrame은 scroll 애니메이션에 throttle 대용으로 자주 사용

🔗 참고 자료