💻 Dev

🛠️ 처음부터 만드는 Throttle — 일정 시간마다 최대 1회만 실행하기

Debounce와 자주 혼동되지만, Throttle은 다릅니다. Debounce는 마지막 호출을 기다리지만, Throttle은 일정 시간 간격으로 확실하게 실행합니다.

언제 쓰나?


```javascript
window.addEventListener('scroll', handleScroll); // 초당 60회 호출됨 — 너무 많음!
window.addEventListener('scroll', throttle(handleScroll, 200)); // 200ms마다 최대 1회
```
리사이즈, 마우스 무브, 스크롤, 검색 입력 등 고빈도 이벤트를 제어할 때 필수.

15줄 구현


```javascript
function throttle(fn, delay) {
let lastCall = 0;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return fn(...args);
}
};
}
// 사용
const handleScroll = () => console.log('scroll!');
window.addEventListener('scroll', throttle(handleScroll, 200));
```

실무 팁


Debounce vs Throttle
  • Debounce: 타이핑 완료 후 검색 → 한 번 실행

  • Throttle: 스크롤 중 위치 추적 → 주기적으로 실행

  • 성능 효과
  • 이벤트 핸들러 호출 수: 60회/초 → 5회/초 (200ms 기준) = 92% 감소

  • 프레임 드롭/렉 제거

  • 📚 더 알아보기: [Lodash throttle](https://lodash.com/docs#throttle)
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!