처음부터 만드는 Throttle — lodash-style 일정 간격 실행기
Throttle vs Debounce
Debounce는 "마지막 호출 이후 지정 시간 지나면 실행", Throttle은 "N초마다 최대 1번만 실행"입니다.
```javascript
// Debounce: 입력 멈춘 후 500ms 뒤에 한 번
window.addEventListener('resize', debounce(() => {
console.log('사이즈 조정 완료');
}, 500));
// Throttle: 스크롤 중 300ms마다 최대 1번
window.addEventListener('scroll', throttle(() => {
console.log('스크롤 위치:', window.scrollY);
}, 300));
```
핵심: 마지막 실행 시간 기록
```javascript
function throttle(fn, wait) {
let lastCall = 0;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= wait) {
lastCall = now;
fn(...args);
}
};
}
```
주요 포인트:
레딩 엣지(Leading) & 트레일링 엣지(Trailing)
```javascript
function throttle(fn, wait, { leading = true, trailing = false } = {}) {
let lastCall = leading ? 0 : Date.now();
let timeoutId = null;
return function throttled(...args) {
const now = Date.now();
if (!leading && !lastCall) lastCall = now;
if (now - lastCall >= wait) {
lastCall = now;
fn(...args);
} else if (trailing && !timeoutId) {
timeoutId = setTimeout(() => {
lastCall = Date.now();
fn(...args);
timeoutId = null;
}, wait - (now - lastCall));
}
};
}
```
실전 예제
```javascript
// 마우스 무브: 300ms마다 좌표 업데이트
const handleMouseMove = throttle((e) => {
console.log(`X: ${e.clientX}, Y: ${e.clientY}`);
}, 300);
window.addEventListener('mousemove', handleMouseMove);
// 스크롤: 100ms마다 스크롤 위치 체크
const handleScroll = throttle(() => {
const scrollPercent = (window.scrollY / document.body.scrollHeight) * 100;
updateProgressBar(scrollPercent);
}, 100, { trailing: true });
window.addEventListener('scroll', handleScroll);
```
언제 쓸까?
| 상황 | 선택 |
|------|------|
| 입력 지연 후 최종 값만 필요 | Debounce |
| 이벤트 급발생 시 성능 최적화 | Throttle |
| 마우스/터치 이동 추적 | Throttle |
| 스크롤 감지 | Throttle |
| 검색 입력 자동완성 | Debounce |
| API 호출 제한 | Throttle |
참고: 최신 브라우저 API인 `requestAnimationFrame` + Throttle 조합으로 더 부드러운 애니메이션 가능!
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!