🛠️ 처음부터 만드는 Throttle — 일정 시간마다 최대 1회만 실행하기
언제 쓰나?
```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
성능 효과
📚 더 알아보기: [Lodash throttle](https://lodash.com/docs#throttle)
Comments (0)
💬
No comments yet.
Be the first to comment!