🛠️ 처음부터 만드는 Debounce — 빠른 연속 호출을 마지막 한 번만 실행하기
Debounce는 연속으로 빠르게 발생하는 이벤트에서 마지막 호출만 실행하는 함수입니다. 검색창 자동완성, 윈도우 리사이즈, 자동저장 같은 곳에서 필수적이에요.
```javascript
const handleSearch = (query) => {
console.log('API 호출:', query);
};
input.addEventListener('input', handleSearch);
// "hello" 입력 → h, he, hel, hel, hell, hello
// API 5번 호출! 🔥
```
```javascript
function debounce(fn, delay) {
let timeout;
return function debounced(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
// 사용
const debouncedSearch = debounce((query) => {
console.log('API 호출:', query);
}, 300);
input.addEventListener('input', (e) => {
debouncedSearch(e.target.value);
});
// "hello" 입력 → 300ms 대기 후 마지막 상태("hello") 한 번만 API 호출 ✅
```
```javascript
function debounce(fn, delay) {
let timeout;
return function debounced(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, args); // 원본 this 보존
}, delay);
};
}
const user = {
name: 'Alice',
log: debounce(function(msg) {
console.log(`${this.name}: ${msg}`);
}, 300)
};
user.log('안녕'); // "Alice: 안녕" ✅
```
```javascript
const autoSave = debounce(async (content) => {
console.log('저장 중...');
await fetch('/api/save', {
method: 'POST',
body: JSON.stringify({ content })
});
console.log('저장 완료!');
}, 1000);
editor.addEventListener('input', (e) => {
autoSave(e.target.value);
});
// 타이핑 멈춘 후 1초 뒤 한 번만 저장
```
Throttle: 일정 시간 간격으로 실행 (스크롤 모니터링)
Debounce: 마지막 호출 후 일정 시간 뒤 실행 (검색, 자동저장)
참고: Lodash의 [debounce](https://lodash.com/docs/4.17.21#debounce) 문서에서 `leading/trailing` 옵션을 확인하면, 즉시 실행 후 지연 실행도 조합할 수 있습니다.
문제: 불필요한 연속 호출
```javascript
const handleSearch = (query) => {
console.log('API 호출:', query);
};
input.addEventListener('input', handleSearch);
// "hello" 입력 → h, he, hel, hel, hell, hello
// API 5번 호출! 🔥
```
솔루션: Debounce 함수
```javascript
function debounce(fn, delay) {
let timeout;
return function debounced(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
// 사용
const debouncedSearch = debounce((query) => {
console.log('API 호출:', query);
}, 300);
input.addEventListener('input', (e) => {
debouncedSearch(e.target.value);
});
// "hello" 입력 → 300ms 대기 후 마지막 상태("hello") 한 번만 API 호출 ✅
```
this 바인딩 유지하기
```javascript
function debounce(fn, delay) {
let timeout;
return function debounced(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
fn.apply(this, args); // 원본 this 보존
}, delay);
};
}
const user = {
name: 'Alice',
log: debounce(function(msg) {
console.log(`${this.name}: ${msg}`);
}, 300)
};
user.log('안녕'); // "Alice: 안녕" ✅
```
실전 예제: 자동저장
```javascript
const autoSave = debounce(async (content) => {
console.log('저장 중...');
await fetch('/api/save', {
method: 'POST',
body: JSON.stringify({ content })
});
console.log('저장 완료!');
}, 1000);
editor.addEventListener('input', (e) => {
autoSave(e.target.value);
});
// 타이핑 멈춘 후 1초 뒤 한 번만 저장
```
Throttle vs Debounce
참고: Lodash의 [debounce](https://lodash.com/docs/4.17.21#debounce) 문서에서 `leading/trailing` 옵션을 확인하면, 즉시 실행 후 지연 실행도 조합할 수 있습니다.
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!