디바운스(debounce) 쓰로틀링(throttling)

진성대·2023년 9월 20일
0

Front-End

목록 보기
15/15

스크롤 이벤트를 사용할 때 많은 요청을 방지하기 위해 디바운스(debounce) 또는 쓰로틀링(throttling)을 적용

스크롤 이벤트를 사용할 때 많은 요청을 방지하기 위해 디바운스(debounce) 또는 쓰로틀링(throttling)을 적용하는 것은 좋은 선택입니다. 이 두 기법은 빈번한 이벤트 트리거를 제한하는 방식으로 작동하며, 특히 스크롤 이벤트와 같이 빠르게 연속해서 발생하는 이벤트에 유용합니다.

디바운스 (Debounce)

일정 시간 동안 연속된 호출을 그룹화하여 마지막 함수 호출 후 일정 시간이 지나면 한 번만 실행됩니다.
쓰로틀링 (Throttling)

일정 시간 간격으로 한 번만 실행됩니다. 예를 들면, 100ms 간격으로 실행되도록 설정하면, 100ms 동안 여러 번 호출되더라도 한 번만 실행됩니다.
디바운스 예제:

function debounce(func, delay) {
    let inDebounce;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(inDebounce);
        inDebounce = setTimeout(() => func.apply(context, args), delay);
    }
}

let loadMoreDataDebounced = debounce(loadMoreData, 300); // 300ms 딜레이

scrollContainer.addEventListener('scroll', function() {
    if (scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight) {
        loadMoreDataDebounced();
    }
});

쓰로틀링 예제:

function throttle(func, limit) {
    let inThrottle;
    return function() {
        const context = this;
        const args = arguments;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

let loadMoreDataThrottled = throttle(loadMoreData, 300); // 300ms 간격

scrollContainer.addEventListener('scroll', function() {
    if (scrollContainer.scrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight) {
        loadMoreDataThrottled();
    }
});

위의 예제에서는 300ms를 기준으로 했지만, 원하는 딜레이나 간격을 설정할 수 있습니다. 디바운스와 쓰로틀링 중 어느 것을 사용할지는 상황에 따라 결정해야 합니다.

스크롤 이벤트에 대한 데이터 로딩 같은 경우, 디바운스가 더 적절할 수 있습니다. 왜냐하면 사용자가 스크롤을 멈출 때까지 데이터를 로드하지 않기를 원할 수 있기 때문입니다.

profile
신입 개발자

0개의 댓글