🛠️ 처음부터 만드는 Debounce — 연속 입력을 마지막 한 번만 실행하기
# Debounce 만들기
Debounce는 연속 호출을 무시하고, 마지막 호출만 지정된 시간 후에 실행합니다. 검색 입력, 자동저장, 창 리사이즈 같은 이벤트에서 불필요한 함수 호출을 줄일 때 씁니다.
```javascript
function debounce(func, delay) {
let timeoutId;
return function debounced(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// 사용 예
const search = debounce((query) => {
console.log('API 호출:', query);
}, 500);
search('a'); // 무시됨
search('ab'); // 무시됨
search('abc'); // 500ms 후 실행
```
```javascript
function debounce(func, delay, { leading = false, trailing = true } = {}) {
let timeoutId;
let lastResult;
return function debounced(...args) {
const shouldCallNow = leading && !timeoutId;
clearTimeout(timeoutId);
if (shouldCallNow) {
lastResult = func.apply(this, args);
}
timeoutId = setTimeout(() => {
if (trailing) {
lastResult = func.apply(this, args);
}
timeoutId = null;
}, delay);
return lastResult;
};
}
// 버튼 클릭: 첫 클릭 즉시 + 마지막 클릭까지 500ms 대기
const onClick = debounce(handleSave, 500, { leading: true });
```
| 구분 | Debounce | Throttle |
|-----|----------|----------|
| 실행 시점 | 마지막 호출 후 delay | 일정 간격으로 주기적 |
| 사용처 | 검색, 자동저장 | 스크롤, 리사이즈 |
| 동작 | 호출 멈추면 실행 | 주기마다 실행 |
핵심: Throttle은 "자주" 실행되고, Debounce는 "마지막에만" 실행됩니다.
```javascript
// React에서 자동저장
const [content, setContent] = useState('');
const saveContent = debounce((text) => {
fetch('/api/save', { method: 'POST', body: text });
}, 2000);
const handleChange = (e) => {
setContent(e.target.value);
saveContent(e.target.value);
};
```
참고: [Lodash debounce](https://lodash.com/docs/#debounce)
Debounce는 연속 호출을 무시하고, 마지막 호출만 지정된 시간 후에 실행합니다. 검색 입력, 자동저장, 창 리사이즈 같은 이벤트에서 불필요한 함수 호출을 줄일 때 씁니다.
기본 구현
```javascript
function debounce(func, delay) {
let timeoutId;
return function debounced(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
// 사용 예
const search = debounce((query) => {
console.log('API 호출:', query);
}, 500);
search('a'); // 무시됨
search('ab'); // 무시됨
search('abc'); // 500ms 후 실행
```
고급 버전: leading/trailing 옵션
```javascript
function debounce(func, delay, { leading = false, trailing = true } = {}) {
let timeoutId;
let lastResult;
return function debounced(...args) {
const shouldCallNow = leading && !timeoutId;
clearTimeout(timeoutId);
if (shouldCallNow) {
lastResult = func.apply(this, args);
}
timeoutId = setTimeout(() => {
if (trailing) {
lastResult = func.apply(this, args);
}
timeoutId = null;
}, delay);
return lastResult;
};
}
// 버튼 클릭: 첫 클릭 즉시 + 마지막 클릭까지 500ms 대기
const onClick = debounce(handleSave, 500, { leading: true });
```
Throttle과의 차이
| 구분 | Debounce | Throttle |
|-----|----------|----------|
| 실행 시점 | 마지막 호출 후 delay | 일정 간격으로 주기적 |
| 사용처 | 검색, 자동저장 | 스크롤, 리사이즈 |
| 동작 | 호출 멈추면 실행 | 주기마다 실행 |
핵심: Throttle은 "자주" 실행되고, Debounce는 "마지막에만" 실행됩니다.
실전 예제
```javascript
// React에서 자동저장
const [content, setContent] = useState('');
const saveContent = debounce((text) => {
fetch('/api/save', { method: 'POST', body: text });
}, 2000);
const handleChange = (e) => {
setContent(e.target.value);
saveContent(e.target.value);
};
```
참고: [Lodash debounce](https://lodash.com/docs/#debounce)
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!