💻 Dev

🛠️ 처음부터 만드는 Debounce — 연속 호출을 묶어서 마지막 한 번만 실행하기

Debounce란?


반복적인 이벤트(검색 입력, 윈도우 리사이즈 등)에서 마지막 호출 이후 일정 시간 동안 새 호출이 없어야만 함수를 실행하는 기법입니다.
```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('API 호출:', query);
fetch(`/api/search?q=${query}`);
}, 300);
input.addEventListener('input', (e) => {
handleSearch(e.target.value);
});
```
Throttle과의 차이
  • Throttle: 일정 간격으로 주기적 실행 (100ms마다)

  • Debounce: 마지막 호출 후 지정 시간 경과 시 한 번 실행 (300ms 후)

  • TypeScript 버전


    ```typescript
    function debounce any>(
    fn: T,
    delay: number
    ): (...args: Parameters) => void {
    let timeoutId: NodeJS.Timeout;

    return (...args: Parameters) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn(...args), delay);
    };
    }
    ```
    React에서는 `useCallback` 또는 `react-use`의 `useDebounce` 훅 사용을 권장합니다.
    📚 참고
  • [MDN setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)

  • [Lodash debounce](https://lodash.com/docs/#debounce)
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!