💻 Dev

🛠️ 처음부터 만드는 Throttle — 함수 호출을 일정한 시간 간격으로 제한하기

# Throttle: 함수 호출 빈도 제어하기
Throttle은 함수가 일정한 시간 간격으로 최대 1회만 실행되도록 제한합니다.

언제 필요할까?


스크롤, 리사이즈, 마우스 이동 등 빈번하게 발생하는 이벤트에서:
```javascript
// 스크롤할 때마다 무거운 계산이 수백 번 실행됨
window.addEventListener('scroll', () => {
console.log('스크롤 위치 저장');
});
```
Throttle로 1초에 1번만 실행하면 성능이 크게 개선됩니다.

구현하기


```javascript
function throttle(fn, delay) {
let lastCall = 0;

return function(...args) {
const now = Date.now();

if (now - lastCall >= delay) {
lastCall = now;
return fn.apply(this, args);
}
};
}
// 사용
const handleScroll = throttle(() => {
console.log('스크롤 위치 저장');
}, 1000); // 1초 간격
window.addEventListener('scroll', handleScroll);
```

Debounce와의 차이


  • Throttle: 일정 간격으로 계속 실행 (최소 1회)

  • Debounce: 마지막 호출 후 일정 시간 후 1회만 실행

  • 실전 팁: 스크롤/리사이즈 → Throttle, 검색 입력 → Debounce
    📖 참고: [Lodash throttle](https://lodash.com/docs#throttle)
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!