🛠️ 처음부터 만드는 Throttle — 함수 호출을 일정 간격으로 제한하기
# Throttle: 함수 호출을 일정 간격으로 제한하기
Debounce와 비슷하지만 다른 패턴입니다. 일정 시간마다 최대 1회만 함수를 실행합니다.
마우스 드래그 이벤트 처리
스크롤 이벤트 성능 최적화
API 요청 rate limiting
게임 렌더링 fps 제어
```javascript
function throttle(func, delay) {
let lastCall = 0;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return func(...args);
}
};
}
// 사용 예시
const handleScroll = throttle(() => {
console.log('스크롤 위치:', window.scrollY);
}, 1000); // 1초마다 최대 1회
window.addEventListener('scroll', handleScroll);
```
| 구분 | Debounce | Throttle |
|------|----------|----------|
| 실행 | 마지막 호출 후 delay | 일정 간격마다 |
| 사용처 | 검색 입력 | 스크롤, 드래그 |
| 특징 | 연속 이벤트 무시 | 일정 속도 유지 |
```javascript
function throttle(func, delay, options = {}) {
let lastCall = options.leading ? -delay : 0;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return func(...args);
}
};
}
// 첫 호출 즉시 실행
const handler = throttle(expensiveOp, 1000, { leading: true });
```
실제 프로젝트: [Lodash throttle](https://lodash.com/docs/#throttle) 참고 후 필요시 도입하세요.
Debounce와 비슷하지만 다른 패턴입니다. 일정 시간마다 최대 1회만 함수를 실행합니다.
언제 쓸까?
```javascript
function throttle(func, delay) {
let lastCall = 0;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return func(...args);
}
};
}
// 사용 예시
const handleScroll = throttle(() => {
console.log('스크롤 위치:', window.scrollY);
}, 1000); // 1초마다 최대 1회
window.addEventListener('scroll', handleScroll);
```
Debounce와의 차이
| 구분 | Debounce | Throttle |
|------|----------|----------|
| 실행 | 마지막 호출 후 delay | 일정 간격마다 |
| 사용처 | 검색 입력 | 스크롤, 드래그 |
| 특징 | 연속 이벤트 무시 | 일정 속도 유지 |
심화: 첫 호출 즉시 실행
```javascript
function throttle(func, delay, options = {}) {
let lastCall = options.leading ? -delay : 0;
return function throttled(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
return func(...args);
}
};
}
// 첫 호출 즉시 실행
const handler = throttle(expensiveOp, 1000, { leading: true });
```
실제 프로젝트: [Lodash throttle](https://lodash.com/docs/#throttle) 참고 후 필요시 도입하세요.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!