🛠️ 처음부터 만드는 Throttle — 연속 이벤트를 시간 간격으로 제한하기
# Throttle: 시간 간격으로 함수 실행 제한하기
Debounce와 다릅니다.
Debounce: 마지막 이벤트 기준으로 대기
Throttle: 일정 시간마다 최대 1번 실행
스크롤, 윈도우 리사이징, 마우스 움직임 같은 고빈도 이벤트에서 필수적입니다.
```javascript
function throttle(fn, wait) {
let lastCall = 0;
let timeout = null;
return function throttled(...args) {
const now = Date.now();
const remaining = wait - (now - lastCall);
// 대기 시간이 경과했으면 즉시 실행
if (remaining <= 0) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
lastCall = now;
fn.apply(this, args);
}
// 아직 대기 중이고, 예약되지 않았으면 마지막 호출 스케줄
else if (!timeout) {
timeout = setTimeout(() => {
lastCall = Date.now();
timeout = null;
fn.apply(this, args);
}, remaining);
}
};
}
```
```javascript
// 윈도우 리사이징 — 최대 0.5초마다 한 번
const handleResize = throttle(() => {
console.log('윈도우 크기:', window.innerWidth);
}, 500);
window.addEventListener('resize', handleResize);
// 무한 스크롤 — 최대 1초마다 한 번
const handleScroll = throttle(() => {
if (isAtBottom()) loadMore();
}, 1000);
window.addEventListener('scroll', handleScroll);
```
```javascript
function throttle(fn, wait, options = {}) {
let lastCall = options.leading ? 0 : Infinity;
let timeout = null;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= wait) {
lastCall = now;
fn.apply(this, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(() => {
lastCall = Date.now();
timeout = null;
fn.apply(this, args);
}, wait - (now - lastCall));
}
};
}
// 첫 호출 제외, 마지막만 실행
const fn = throttle(callback, 500, { leading: false });
```
1. Throttle vs Debounce: 주기적 업데이트는 throttle, 최종 결과는 debounce
2. 리액트에서: useCallback + ref로 조합하거나 useMemo 활용
3. lodash: `_.throttle(fn, 500)`으로도 사용 가능
4. 클린업: 컴포넌트 언마운트 시 timeout 제거 필수
Debounce와 다릅니다.
스크롤, 윈도우 리사이징, 마우스 움직임 같은 고빈도 이벤트에서 필수적입니다.
기본 구현
```javascript
function throttle(fn, wait) {
let lastCall = 0;
let timeout = null;
return function throttled(...args) {
const now = Date.now();
const remaining = wait - (now - lastCall);
// 대기 시간이 경과했으면 즉시 실행
if (remaining <= 0) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
lastCall = now;
fn.apply(this, args);
}
// 아직 대기 중이고, 예약되지 않았으면 마지막 호출 스케줄
else if (!timeout) {
timeout = setTimeout(() => {
lastCall = Date.now();
timeout = null;
fn.apply(this, args);
}, remaining);
}
};
}
```
실제 사용 예
```javascript
// 윈도우 리사이징 — 최대 0.5초마다 한 번
const handleResize = throttle(() => {
console.log('윈도우 크기:', window.innerWidth);
}, 500);
window.addEventListener('resize', handleResize);
// 무한 스크롤 — 최대 1초마다 한 번
const handleScroll = throttle(() => {
if (isAtBottom()) loadMore();
}, 1000);
window.addEventListener('scroll', handleScroll);
```
고급: Options 객체로 유연성 추가
```javascript
function throttle(fn, wait, options = {}) {
let lastCall = options.leading ? 0 : Infinity;
let timeout = null;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= wait) {
lastCall = now;
fn.apply(this, args);
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(() => {
lastCall = Date.now();
timeout = null;
fn.apply(this, args);
}, wait - (now - lastCall));
}
};
}
// 첫 호출 제외, 마지막만 실행
const fn = throttle(callback, 500, { leading: false });
```
실무 팁
1. Throttle vs Debounce: 주기적 업데이트는 throttle, 최종 결과는 debounce
2. 리액트에서: useCallback + ref로 조합하거나 useMemo 활용
3. lodash: `_.throttle(fn, 500)`으로도 사용 가능
4. 클린업: 컴포넌트 언마운트 시 timeout 제거 필수
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!