🛠️ 처음부터 만드는 Debounce — 연속 호출을 묶어서 마지막 한 번만 실행하기
Debounce란?
반복적인 이벤트(검색 입력, 윈도우 리사이즈 등)에서 마지막 호출 이후 일정 시간 동안 새 호출이 없어야만 함수를 실행하는 기법입니다.
```javascript
function debounce(fn, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
```
실제 사용 예제
```javascript
const handleSearch = debounce((query) => {
console.log('API 호출:', query);
fetch(`/api/search?q=${query}`);
}, 300);
input.addEventListener('input', (e) => {
handleSearch(e.target.value);
});
```
Throttle과의 차이
TypeScript 버전
```typescript
function debounce
fn: T,
delay: number
): (...args: Parameters
let timeoutId: NodeJS.Timeout;
return (...args: Parameters
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
```
React에서는 `useCallback` 또는 `react-use`의 `useDebounce` 훅 사용을 권장합니다.
📚 참고
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!