🛠️ 처음부터 만드는 Throttle — 연속 호출을 일정 간격으로 제한하기
# Throttle 이해하기
Throttle은 연속으로 들어오는 함수 호출을 일정 시간 간격으로 제한하는 기법입니다. Debounce와 달리, 마지막 호출을 기다리지 않고 정기적으로 실행합니다.
스크롤 이벤트 처리 (infinite scroll, parallax)
마우스/터치 움직임 추적
윈도우 리사이즈 감지
자동 저장 (일정 간격)
API 폴링 (rate limiting)
```
Debounce: ━━━━━ X X X ✓ (마지막에 1번)
Throttle: ✓ ━━━━ ✓ ━━━ ✓ (일정 간격마다)
```
```typescript
function throttle any>(
func: T,
delay: number
): T {
let lastRun = 0;
let timeout: NodeJS.Timeout | null = null;
return ((...args: any[]) => {
const now = Date.now();
const timeSinceLastRun = now - lastRun;
if (timeSinceLastRun >= delay) {
// 충분한 시간이 지났으면 즉시 실행
func(...args);
lastRun = now;
if (timeout) clearTimeout(timeout);
timeout = null;
} else {
// 다음 실행 예약
if (timeout) clearTimeout(timeout);
const remainingTime = delay - timeSinceLastRun;
timeout = setTimeout(() => {
func(...args);
lastRun = Date.now();
timeout = null;
}, remainingTime);
}
}) as T;
}
```
```typescript
// 스크롤 이벤트에 적용
const handleScroll = throttle(() => {
console.log('현재 위치:', window.scrollY);
}, 300); // 300ms마다만 실행
window.addEventListener('scroll', handleScroll);
// 마우스 움직임 추적
const trackMouse = throttle((e: MouseEvent) => {
console.log(`X: ${e.clientX}, Y: ${e.clientY}`);
}, 100); // 100ms마다만 업데이트
document.addEventListener('mousemove', trackMouse);
```
Throttle: 화면 갱신 같은 주기적 처리가 필요할 때
Debounce: 검색 입력 같은 최종 상태 결정 후에만 실행할 때
팁: 모던 브라우저의 `requestAnimationFrame()`과 함께 쓰면 성능이 더 좋습니다!
Throttle은 연속으로 들어오는 함수 호출을 일정 시간 간격으로 제한하는 기법입니다. Debounce와 달리, 마지막 호출을 기다리지 않고 정기적으로 실행합니다.
사용 사례
Debounce vs Throttle
```
Debounce: ━━━━━ X X X ✓ (마지막에 1번)
Throttle: ✓ ━━━━ ✓ ━━━ ✓ (일정 간격마다)
```
구현하기
```typescript
function throttle
func: T,
delay: number
): T {
let lastRun = 0;
let timeout: NodeJS.Timeout | null = null;
return ((...args: any[]) => {
const now = Date.now();
const timeSinceLastRun = now - lastRun;
if (timeSinceLastRun >= delay) {
// 충분한 시간이 지났으면 즉시 실행
func(...args);
lastRun = now;
if (timeout) clearTimeout(timeout);
timeout = null;
} else {
// 다음 실행 예약
if (timeout) clearTimeout(timeout);
const remainingTime = delay - timeSinceLastRun;
timeout = setTimeout(() => {
func(...args);
lastRun = Date.now();
timeout = null;
}, remainingTime);
}
}) as T;
}
```
실제 사용 예제
```typescript
// 스크롤 이벤트에 적용
const handleScroll = throttle(() => {
console.log('현재 위치:', window.scrollY);
}, 300); // 300ms마다만 실행
window.addEventListener('scroll', handleScroll);
// 마우스 움직임 추적
const trackMouse = throttle((e: MouseEvent) => {
console.log(`X: ${e.clientX}, Y: ${e.clientY}`);
}, 100); // 100ms마다만 업데이트
document.addEventListener('mousemove', trackMouse);
```
언제 쓸까?
팁: 모던 브라우저의 `requestAnimationFrame()`과 함께 쓰면 성능이 더 좋습니다!
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!