🛠️ 처음부터 만드는 Throttle — 연속 이벤트를 일정 간격으로 제한하기
Throttle이란?
Debounce처럼 함수 호출을 제어하지만, 일정 시간마다 반드시 최소 1번은 실행됩니다.
```
Debounce: [A] ----[B]---- → [B] 최종본만
Throttle: [A]--[A]--[A]--[A] → 매 60ms마다 한 번씩
```
스크롤, 마우스 이동, 창 크기 조정처럼 연속으로 발생하지만 너무 자주 처리하면 낭비인 이벤트에 적합합니다.
기본 구현 (8줄)
```javascript
function throttle(fn, delay) {
let lastCall = 0;
return (...args) => {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn(...args);
}
};
}
```
실제 사용
```javascript
// 스크롤 이벤트: 매 300ms마다 최대 1번만 실행
const handleScroll = throttle(() => {
console.log('스크롤 위치:', window.scrollY);
}, 300);
window.addEventListener('scroll', handleScroll);
// 마우스 추적: 매 50ms마다 위치 갱신
const trackMouse = throttle((e) => {
updateCursorPosition(e.clientX, e.clientY);
}, 50);
document.addEventListener('mousemove', trackMouse);
```
심화: Leading/Trailing 옵션
```javascript
function throttle(fn, delay, options = {}) {
let lastCall = 0, timeout;
const { leading = true, trailing = true } = options;
return (...args) => {
const now = Date.now();
if (!lastCall && !leading) lastCall = now;
if (now - lastCall >= delay) {
lastCall = now;
fn(...args);
clearTimeout(timeout);
} else if (trailing) {
clearTimeout(timeout);
timeout = setTimeout(() => {
lastCall = leading ? Date.now() : 0;
fn(...args);
}, delay - (now - lastCall));
}
};
}
```
참고 자료
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!