💻 Dev

🛠️ 처음부터 만드는 Throttle — 이벤트를 일정 시간마다만 처리하기

Throttle은 연속 이벤트를 일정 시간 간격으로만 처리합니다. Debounce와 다르게 계속 실행됩니다.

문제 상황


```javascript
window.addEventListener('scroll', () => console.log('scroll')); // 초당 60회 호출!
```

기본 구현


```javascript
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
```

사용 예


```javascript
const handleScroll = throttle(() => {
console.log('scroll detected');
}, 1000); // 1초마다만 실행
window.addEventListener('scroll', handleScroll);
```

Debounce vs Throttle


| | Debounce | Throttle |
|---|---|---|
| 실행 시점 | 마지막 호출 후 N초 | 매 N초마다 |
| 사용처 | 검색창, 자동저장 | 스크롤, 리사이즈 |

향상된 버전 (leading/trailing)


```javascript
function throttle(fn, limit, { leading = true, trailing = true } = {}) {
let lastRun = 0, timeout;

return function(...args) {
const now = Date.now();
if (now - lastRun >= limit && leading) {
fn.apply(this, args);
lastRun = now;
} else if (trailing) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, args);
lastRun = Date.now();
}, limit);
}
};
}
```
leading: 첫 호출 즉시 실행, trailing: 마지막 호출도 실행합니다.
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!