🛠️ 처음부터 만드는 Debounce — lodash-style 입력 지연 실행기 15줄 구현
검색창에 키를 누를 때마다 API를 호출하면? 서버가 울고, 사용자 경험도 나빠집니다.
Debounce는 연속 호출을 하나로 묶어 마지막 호출만 실행하는 패턴입니다.
```js
function debounce(fn, ms, { leading = false } = {}) {
let timer, lastArgs;
function debounced(...args) {
lastArgs = args;
if (leading && !timer) fn(...args);
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (!leading) fn(...lastArgs);
}, ms);
}
debounced.cancel = () => { clearTimeout(timer); timer = null; };
debounced.flush = () => { debounced.cancel(); fn(...lastArgs); };
return debounced;
}
```
```js
// 검색 입력 — 300ms 동안 추가 입력 없으면 실행
const search = debounce(q => fetch(`/api?q=${q}`), 300);
input.addEventListener('input', e => search(e.target.value));
// leading: true — 첫 클릭 즉시 실행, 연타 무시
const save = debounce(() => saveDoc(), 1000, { leading: true });
search.cancel(); // 대기 중인 호출 취소
search.flush(); // 즉시 실행
```
```
trailing (기본): --[호출]-[호출]-[호출]---⏰실행
leading: ⚡실행--[호출]-[호출]-------
```
`leading: true`는 첫 호출 즉시 실행 후 쿨다운.
버튼 더블클릭 방지에 딱 맞습니다.
| 기능 | lodash | 우리 구현 |
|------|--------|----------|
| trailing edge | ✅ | ✅ |
| leading edge | ✅ | ✅ |
| cancel / flush | ✅ | ✅ |
| maxWait | ✅ | ❌ |
핵심 기능은 전부 갖췄습니다.
15줄이면 lodash 없이도 입력 최적화 끝!
Debounce는 연속 호출을 하나로 묶어 마지막 호출만 실행하는 패턴입니다.
핵심 구현 (15줄)
```js
function debounce(fn, ms, { leading = false } = {}) {
let timer, lastArgs;
function debounced(...args) {
lastArgs = args;
if (leading && !timer) fn(...args);
clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (!leading) fn(...lastArgs);
}, ms);
}
debounced.cancel = () => { clearTimeout(timer); timer = null; };
debounced.flush = () => { debounced.cancel(); fn(...lastArgs); };
return debounced;
}
```
사용법
```js
// 검색 입력 — 300ms 동안 추가 입력 없으면 실행
const search = debounce(q => fetch(`/api?q=${q}`), 300);
input.addEventListener('input', e => search(e.target.value));
// leading: true — 첫 클릭 즉시 실행, 연타 무시
const save = debounce(() => saveDoc(), 1000, { leading: true });
search.cancel(); // 대기 중인 호출 취소
search.flush(); // 즉시 실행
```
동작 원리
```
trailing (기본): --[호출]-[호출]-[호출]---⏰실행
leading: ⚡실행--[호출]-[호출]-------
```
`leading: true`는 첫 호출 즉시 실행 후 쿨다운.
버튼 더블클릭 방지에 딱 맞습니다.
lodash와 비교
| 기능 | lodash | 우리 구현 |
|------|--------|----------|
| trailing edge | ✅ | ✅ |
| leading edge | ✅ | ✅ |
| cancel / flush | ✅ | ✅ |
| maxWait | ✅ | ❌ |
핵심 기능은 전부 갖췄습니다.
15줄이면 lodash 없이도 입력 최적화 끝!
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!