[JS] debounce, throttle 구현하기

은비·2023년 11월 15일
3

JS_Study

목록 보기
18/18
post-thumbnail

Javascript에서 중요하다고 생각하는 debouncethrottle을 구현해보고
각 기능이 하는 역할을 작성해보려 한다.

Debounce 란?

debounce 기법은 이벤트가 발생한 후 일정 시간 동안 추가 이벤트가 없을 때만 이벤트 핸들러를 실행하는데 사용된다. 사용자의 입력을 처리할 때 유용하다. 사용자가 텍스트 필드에 무언가를 입력하면 이벤트가 발생하는데 debounce를 사용하면 사용자가 입력을 완료하고 일정 시간 동안 다른 이벤트가 발생하지 않을 때만 이벤트 핸들러를 실행하게 된다. 이를 통해 불필요한 이벤트 핸들러의 실행을 줄이는 것이 가능하다.

// 첫번째 방식
const debounce = (cb, delay) => {
  let timer;
  return (...args) => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(cb, delay, ...args);
  };
};

// 사용 예시
window.addEventListener('scroll', debounce(function() {
    console.log('스크롤 하는중!');
}, 250));
// 두번째 방식
const debounce = (func, wait) => {
    let timer;
    return function(...args) {
        const context = this;
        clearTimeout(timer);
        timer = setTimeout(() => func.apply(context, args), wait);
    };
}

Throttle 이란?

throttle 기법은 이벤트 핸들러가 일정 시간 간격으로 한 번만 실행되도록 제한한다. 스크롤 이벤트나 마우스 이동 이벤트와 같이 빈번하게 발생하는 이벤트를 처리할 때 유용하다. throttle을 사용하면 이벤트 핸들러가 너무 자주 실행되는 것을 방지하고, 성능 이슈를 줄일 수 있다.

// 첫번째 방식
const throttle = (cb, delay) => {
  let timer;
  return (...args) => {
    if (timer) return;
    timer = setTimeout(() => {
      cb(...args);
      timer = null;
    }, delay);
  };
};

// 사용 예시
window.addEventListener('resize', throttle(function() {
    console.log('창크기 조정중');
}, 250));
// 두번째 방식
const throttle = (cb, delay) => {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            cb.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, delay);
        }
    }
}

0개의 댓글

관련 채용 정보