🛠️ 처음부터 만드는 Throttle — 일정 간격으로 함수 호출 제한하기
왜 필요한가?
스크롤, 리사이즈, 마우스 이동 같은 이벤트는 매우 자주 발생한다. 매번 반응하면 성능이 떨어진다.
Throttle은 일정 시간 간격마다만 함수를 실행한다. Debounce와 달리, 이벤트가 계속 발생해도 최소 주기마다 한 번은 실행된다.
```typescript
// 20줄 구현
function throttle
func: T,
limit: number
): (...args: Parameters
let last = 0;
return (...args: Parameters
const now = Date.now();
if (now - last >= limit) {
last = now;
func(...args);
}
};
}
```
실전 예제
```typescript
// 스크롤 이벤트 — 100ms마다만 체크
const handleScroll = throttle(() => {
console.log('Scroll:', window.scrollY);
}, 100);
window.addEventListener('scroll', handleScroll);
// API 요청 — 500ms 간격 제한
const search = throttle(async (query: string) => {
const res = await fetch(`/api/search?q=${query}`);
return res.json();
}, 500);
input.addEventListener('input', (e) => search(e.target.value));
```
Debounce와의 차이
| 상황 | Debounce | Throttle |
|------|----------|----------|
| 마지막 이벤트만 처리 | ✅ | ❌ |
| 일정 주기마다 실행 | ❌ | ✅ |
| 검색 자동완성 | 좋음 | - |
| 스크롤 감지 | - | 좋음 |
언제 쓸까?
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!