디바운스, 쓰로틀링

·2024년 8월 16일

자바스크립트

목록 보기
19/21

Debounce와 Throttling은 잦은 이벤트 발생에 따른 성능 이슈를 완화하는데 쓰인다.

Debounce 디바운스

마지막 이벤트를 처리한다.

De + bounce 튀지 않는다. -> 주기, 간격이 없다. -> 제일 끝 이벤트만 처리.

function debounce(func, wait) {
    let timeout;
    return function(...args) {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, args), wait);
    };
}

// 사용 예제
const handleSearch = debounce((query) => {
    console.log('검색 요청:', query);
}, 300);

쓰이는 예시 : 사용자 입력 처리

Throttling 쓰로틀링

일정한 간격으로 이벤트를 처리한다.

throttle 자동차 조절판 -> 일정 간격으로 나눠져 있음 -> 일정 간격으로 이벤트 처리.

function throttle(func, limit) {
    let lastFunc;
    let lastRan;
    return function(...args) {
        const context = this;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(function() {
                if ((Date.now() - lastRan) >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
}

// 사용 예제
const handleScroll = throttle(() => {
    console.log('스크롤 이벤트 처리');
}, 200);

쓰이는 예시 : 스크롤


👁‍🗨

  1. 디바운스와 스로틀의 차이점과 활용 방법
  2. 디바운싱과 쓰로틀링 이해하기
profile
'한 번 더!'의 가능성을 믿어! 오늘도 열심히 굴러가 보는 프론트엔드 개발자 😎

0개의 댓글