💻 Dev

🛠️ 처음부터 만드는 Debounce — 함수 호출을 지연 후 한 번만 실행하기

# Debounce란?
Debounce는 함수 호출을 지연시켰다가, 마지막 호출 이후 일정 시간이 지나면 한 번만 실행하는 패턴입니다. 검색 입력, 윈도우 리사이즈, 자동 저장 등에서 불필요한 호출을 줄일 때 사용합니다.
Throttle과의 차이:
  • Throttle: 일정 시간마다 실행 (3번 호출 → 2번 실행)

  • Debounce: 마지막 호출 이후 대기 (3번 호출 → 1번 실행)

  • 기본 구현


    ```javascript
    function debounce(fn, delay) {
    let timeoutId;

    return function debounced(...args) {
    // 이전 타이머 취소
    clearTimeout(timeoutId);

    // 새 타이머 시작
    timeoutId = setTimeout(() => {
    fn.apply(this, args);
    }, delay);
    };
    }
    // 사용
    const handleSearch = debounce((query) => {
    console.log('검색:', query);
    }, 500);
    document.querySelector('input').addEventListener('input', (e) => {
    handleSearch(e.target.value);
    });
    ```

    고급: Cancel 기능


    실행 대기 중인 함수를 즉시 취소할 수 있도록 개선:
    ```javascript
    function debounce(fn, delay) {
    let timeoutId;

    const debounced = function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => fn.apply(this, args), delay);
    };

    debounced.cancel = () => clearTimeout(timeoutId);
    debounced.flush = () => {
    clearTimeout(timeoutId);
    fn.apply(this, args);
    };

    return debounced;
    }
    // 사용
    const search = debounce(handleSearch, 500);
    search('query');
    search.cancel(); // 실행 취소
    search.flush(); // 즉시 실행
    ```

    실전 예제: 자동 저장


    ```javascript
    const autoSave = debounce(async (content) => {
    try {
    await fetch('/api/save', {
    method: 'POST',
    body: JSON.stringify({ content })
    });
    console.log('저장 완료');
    } catch (err) {
    console.error('저장 실패:', err);
    }
    }, 1000);
    textarea.addEventListener('input', (e) => {
    autoSave(e.target.value);
    });
    ```

    주의사항


  • `this` 바인딩을 유지하려면 arrow function이 아닌 `function` 선언 필수

  • 비동기 작업(API 호출)에 유용하지만, 응답 오류 처리 필수

  • 페이지 떠날 때는 `flush()` 호출로 마지막 작업 보장

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

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!