🛠️ 처음부터 만드는 Throttle — 이벤트를 일정 시간 간격으로만 실행하기
Throttle은 반복되는 이벤트를 일정 시간 간격으로만 실행하도록 제한합니다. Debounce와 달리 주기적으로 실행되므로, 스크롤·리사이즈·마우스 움직임 같은 지속적인 이벤트에 유용합니다.
```javascript
function throttle(fn, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn(...args);
}
};
}
// 사용 예
const handleScroll = throttle(() => {
console.log('Scroll event');
}, 1000);
window.addEventListener('scroll', handleScroll);
// 1초에 최대 1번만 실행
```
마지막 호출도 실행하고 싶다면:
```javascript
function throttle(fn, delay, { trailing = true } = {}) {
let lastCall = 0;
let timeout;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn(...args);
clearTimeout(timeout);
} else if (trailing) {
clearTimeout(timeout);
timeout = setTimeout(() => {
lastCall = Date.now();
fn(...args);
}, delay - (now - lastCall));
}
};
}
```
```javascript
const onResize = throttle(() => {
console.log('Window resized');
}, 300);
window.addEventListener('resize', onResize);
```
Debounce vs Throttle: Debounce는 입력이 멈춘 후 실행되고, Throttle은 주기적으로 실행됩니다. 자동 저장이면 Throttle, 검색 자동완성이면 Debounce를 선택하세요.
[더 알아보기: MDN Throttling and Debouncing](https://developer.mozilla.org/en-US/docs/Glossary/throttle)
기본 구현
```javascript
function throttle(fn, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn(...args);
}
};
}
// 사용 예
const handleScroll = throttle(() => {
console.log('Scroll event');
}, 1000);
window.addEventListener('scroll', handleScroll);
// 1초에 최대 1번만 실행
```
고급: 트레일링 실행
마지막 호출도 실행하고 싶다면:
```javascript
function throttle(fn, delay, { trailing = true } = {}) {
let lastCall = 0;
let timeout;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
fn(...args);
clearTimeout(timeout);
} else if (trailing) {
clearTimeout(timeout);
timeout = setTimeout(() => {
lastCall = Date.now();
fn(...args);
}, delay - (now - lastCall));
}
};
}
```
실제 사용 사례
```javascript
const onResize = throttle(() => {
console.log('Window resized');
}, 300);
window.addEventListener('resize', onResize);
```
Debounce vs Throttle: Debounce는 입력이 멈춘 후 실행되고, Throttle은 주기적으로 실행됩니다. 자동 저장이면 Throttle, 검색 자동완성이면 Debounce를 선택하세요.
[더 알아보기: MDN Throttling and Debouncing](https://developer.mozilla.org/en-US/docs/Glossary/throttle)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!