💻 Dev

🛠️ 처음부터 만드는 Debounce — 마지막 호출만 실행하기

Debounce란?


연속된 호출 중 마지막 호출만 실행하는 함수입니다. 검색 입력창의 자동완성, 윈도우 리사이즈 이벤트 처리 등에서 불필요한 실행을 줄여줍니다.
Throttle이 "일정 간격마다 실행"이라면, Debounce는 "조용해진 후 실행"입니다.

구현


```typescript
function debounce any>(
fn: T,
delay: number
): (...args: Parameters) => void {
let timerId: ReturnType | null = null;
return function (this: any, ...args: Parameters) {
if (timerId !== null) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
fn.apply(this, args);
timerId = null;
}, delay);
};
}
```

핵심 원리


1. 호출될 때마다 이전 타이머를 취소한다
2. 새 타이머를 등록한다
3. `delay` 동안 추가 호출이 없으면 비로소 실행한다

사용 예시


```typescript
const search = debounce((query: string) => {
console.log(`API 호출: ${query}`);
}, 300);
// 빠르게 타이핑하면 마지막 한 번만 실행
search("r");
search("re");
search("rea");
search("reac");
search("react"); // → 300ms 후 "API 호출: react" 한 번만 출력
```

Throttle vs Debounce


| | Throttle | Debounce |
|---|---|---|
| 실행 시점 | 첫 호출 즉시 | 마지막 호출 후 대기 |
| 보장 | 일정 간격 실행 | 연속 입력 종료 후 실행 |
| 적합한 곳 | 스크롤, 드래그 | 검색 입력, 폼 검증 |

참고


  • [MDN - setTimeout](https://developer.mozilla.org/ko/docs/Web/API/setTimeout)

  • Lodash [`_.debounce`](https://lodash.com/docs/4.17.15#debounce)는 `leading`, `trailing`, `maxWait` 옵션도 지원합니다.
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!