💻 Dev

🛠️ 처음부터 만드는 Throttle — 함수 호출을 일정 간격으로 제한하기

Throttle이 뭘까요?


Throttle은 함수가 일정한 시간 간격으로만 실행되도록 제한하는 패턴입니다. Debounce와 헷갈리지만 다릅니다:
  • Debounce: 마지막 호출 후 N초 뒤에 한 번만 실행

  • Throttle: 매 N초마다 최대 한 번씩 실행

  • 스크롤, 마우스 이동, 윈도우 리사이즈 같이 빠르게 반복되는 이벤트에서 자주 쓰입니다.

    구현해보기


    ```javascript
    function throttle(func, delay) {
    let lastCall = 0;

    return function (...args) {
    const now = Date.now();

    if (now - lastCall >= delay) {
    lastCall = now;
    func.apply(this, args);
    }
    };
    }
    // 사용 예
    const handleScroll = throttle(() => {
    console.log('스크롤 처리 중...');
    }, 1000);
    window.addEventListener('scroll', handleScroll);
    ```

    더 나은 버전 (trailing call 지원)


    ```javascript
    function throttle(func, delay) {
    let lastCall = 0;
    let timeout = null;

    return function (...args) {
    const now = Date.now();

    if (now - lastCall >= delay) {
    lastCall = now;
    func.apply(this, args);
    clearTimeout(timeout);
    } else {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
    lastCall = Date.now();
    func.apply(this, args);
    }, delay - (now - lastCall));
    }
    };
    }
    ```

    언제 쓸까?


  • API 호출이 많은 검색창

  • 스크롤 이벤트 처리

  • 마우스/터치 이벤트 (게임, 드래그)

  • 윈도우 리사이즈

  • 더 깊이 있는 구현은 [Lodash 문서](https://lodash.com/docs/#throttle)를 참고하세요.
    💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!