💻 Dev

💻 오늘의 코드 팁 — Throttle

문제: 마우스 이동 이벤트로 무한 요청 발생


```javascript
// ❌ 문제: mousemove 이벤트가 초당 60회 이상 발생
// → API 요청이 무한정 쌓임
document.addEventListener('mousemove', (e) => {
fetch(`/api/track?x=${e.clientX}&y=${e.clientY}`);
});
```
결과: 성능 저하, 네트워크 낭비, 서버 부하 증가
---

해결: Throttle로 실행 주기 제한


```javascript
// ✅ Throttle 구현: 정해진 시간마다 최대 1회만 실행
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// 사용: 250ms마다 최대 1회만 실행
const throttledTrack = throttle((e) => {
fetch(`/api/track?x=${e.clientX}&y=${e.clientY}`);
}, 250);
document.addEventListener('mousemove', throttledTrack);
```
---

Debounce vs Throttle


| 개념 | 실행 시점 | 사용 사례 |
|-----|---------|----------|
| Throttle | 주기적으로 실행 | 스크롤 감지, 마우스 추적, 리사이즈 |
| Debounce | 입력 멈춘 후 1회 | 검색 입력, API 호출 |
Throttle 타임라인 (250ms 주기):
```
이벤트: ▓▓▓▓▓▓▓▓▓▓▓▓▓ (무한 발생)
실행: ▓ ▓ ▓ (250ms마다 1회)
```
---

고급: Leading/Trailing 옵션


```javascript
function throttle(func, limit, options = {}) {
let inThrottle, lastRan;
const { leading = true, trailing = true } = options;
return function(...args) {
const now = Date.now();

// leading: true → 첫 실행은 즉시
if (!lastRan && leading) {
func.apply(this, args);
lastRan = now;
} else if (now - lastRan >= limit) {
func.apply(this, args);
lastRan = now;
}
};
}
// 예: 마지막 이벤트만 처리
const throttled = throttle(handleResize, 200, {
leading: false,
trailing: true
});
```
---

실전 예제: 무한 스크롤


```javascript
const throttledScroll = throttle(() => {
const { scrollTop, scrollHeight, clientHeight } = document.documentElement;

// 스크롤이 90% 이상 내려갔을 때만 로드
if (scrollTop + clientHeight >= scrollHeight * 0.9) {
console.log('더 많은 데이터 로드...');
loadMoreData();
}
}, 500); // 500ms마다 최대 1회 체크
window.addEventListener('scroll', throttledScroll);
```
---

🔗 참고 자료


  • [Lodash throttle](https://lodash.com/docs/#throttle) — 프로덕션 레벨 구현

  • [MDN: 성능 최적화](https://developer.mozilla.org/en-US/docs/Web/Performance)

  • [Debounce vs Throttle 시각화](https://redd.one/blog/debounce-vs-throttle)
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!