🛠️ 처음부터 만드는 Debounce — 입력을 지연시켜 최종 값만 처리하기
Debounce란?
연속으로 발생하는 이벤트에서 마지막 이벤트만 처리하는 패턴입니다. 검색 입력, 자동저장, 윈도우 리사이징 같은 상황에 쓰입니다.
Throttle과의 차이
단계별 구현
Step 1: 기본 구조
```javascript
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn(...args), delay);
};
}
```
Step 2: this 바인딩 추가
```javascript
function debounce(fn, delay) {
let timeoutId;
return function (...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), delay);
};
}
```
실제 사용
```javascript
const handleSearch = debounce((query) => {
console.log('검색:', query);
// API 호출
}, 500);
// 입력 이벤트마다 호출되지만, 500ms 동안 입력이 없어야 실행됨
input.addEventListener('input', (e) => handleSearch(e.target.value));
```
"hello world"를 한 글자씩 입력하면?
간단하지만 강력합니다! 🚀
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!