🛠️ 처음부터 만드는 Throttle — 연속 이벤트를 일정 간격으로만 처리하기
# 🛠️ 처음부터 만드는 Throttle
Debounce와 헷갈리기 쉬운 Throttle을 직접 구현해봅시다.
Debounce: 마지막 호출 후 N초가 지나야 실행 (입력 완료 대기)
Throttle: 최대 N초마다 한 번씩 실행 (일정한 속도 제어)
스크롤할 때 Debounce를 쓰면 마지막 스크롤 후에야 계산이 시작되지만, Throttle을 쓰면 스크롤 중에도 균일하게 반응합니다.
```javascript
function throttle(fn, delay) {
let lastCallTime = 0;
let timeoutId = null;
return function throttled(...args) {
const now = Date.now();
const timeSinceLastCall = now - lastCallTime;
if (timeSinceLastCall >= delay) {
// 지연 시간이 지났으면 즉시 실행
lastCallTime = now;
fn.apply(this, args);
} else {
// 아직 지연 시간이 안 지났으면, 남은 시간 후 실행 예약
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
lastCallTime = Date.now();
fn.apply(this, args);
}, delay - timeSinceLastCall);
}
};
}
// 사용 예시
const handleScroll = throttle(() => {
console.log('스크롤 위치:', window.scrollY);
}, 300);
window.addEventListener('scroll', handleScroll);
const handleMouseMove = throttle((e) => {
console.log('마우스 위치:', e.x, e.y);
}, 100);
document.addEventListener('mousemove', handleMouseMove);
```
1. `lastCallTime`으로 마지막 실행 시점 기록
2. 지연 시간 초과 → 즉시 실행
3. 초과 안 됨 → 타이머로 보류 (마지막 호출까지 대기)
검색 입력: API 요청을 100ms마다만 전송
스크롤/리사이즈: 레이아웃 재계산을 400ms마다만 실행
마우스 움직임: 드래그 추적을 30ms 간격으로만 업데이트
Lodash의 [throttle 문서](https://lodash.com/docs/#throttle)도 참고하세요!
Debounce와 헷갈리기 쉬운 Throttle을 직접 구현해봅시다.
차이점
스크롤할 때 Debounce를 쓰면 마지막 스크롤 후에야 계산이 시작되지만, Throttle을 쓰면 스크롤 중에도 균일하게 반응합니다.
구현
```javascript
function throttle(fn, delay) {
let lastCallTime = 0;
let timeoutId = null;
return function throttled(...args) {
const now = Date.now();
const timeSinceLastCall = now - lastCallTime;
if (timeSinceLastCall >= delay) {
// 지연 시간이 지났으면 즉시 실행
lastCallTime = now;
fn.apply(this, args);
} else {
// 아직 지연 시간이 안 지났으면, 남은 시간 후 실행 예약
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
lastCallTime = Date.now();
fn.apply(this, args);
}, delay - timeSinceLastCall);
}
};
}
// 사용 예시
const handleScroll = throttle(() => {
console.log('스크롤 위치:', window.scrollY);
}, 300);
window.addEventListener('scroll', handleScroll);
const handleMouseMove = throttle((e) => {
console.log('마우스 위치:', e.x, e.y);
}, 100);
document.addEventListener('mousemove', handleMouseMove);
```
핵심 아이디어
1. `lastCallTime`으로 마지막 실행 시점 기록
2. 지연 시간 초과 → 즉시 실행
3. 초과 안 됨 → 타이머로 보류 (마지막 호출까지 대기)
실제 사용처
Lodash의 [throttle 문서](https://lodash.com/docs/#throttle)도 참고하세요!
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!