Programming/React

Debounce & Throttle

i독 2021. 10. 13. 06:37

> Debounce

< Example > Google 연관 검색어 도출 기능

함수 호출 전에 딜레이를 발생시켜, 이전 중복된 호출은 무시하고, 이후 호출의 수행만 이끌어내는 함수.

function debounce(func, delay) {
  let inDebounce;
  return function (...args) {
    if (inDebounce) {
      clearTimeout(inDebounce);
    }
    inDebounce = setTimeout(() => func(...args), delay);
  };
}


const run = debounce((val) => console.log(val), 100);
run('a');
run('b');

 

 

> Throttle - 중복 요청 과정 생략

< Example > Facebook 무한 스크롤 기능 (신규 갱신)

함수 호출이 되는 동안 중복된 요청을 무시하고 실행 이후에 번째로 호출되는 요청을 동일하게 지연 실행하여 구간 내에서

중복 요청 과정을 생략함.

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


var checkPosition = () => {
  const offset = 500;
  const currentScrollPosition = window.pageYOffset;
  const pageBottomPosition = document.body.offsetHeight - window.innerHeight - offset;
  if (currentScrollPosition >= pageBottomPosition) {
    // fetch('/page/next');
    console.log('다음 페이지 로딩');
  }
};
var infiniteScroll = throttle(checkPosition, 300);
window.addEventListener('scroll', infiniteScroll);

'Programming > React' 카테고리의 다른 글

Component Callback&event handling  (0) 2021.10.13
Component 배열 활용  (0) 2021.10.13
Component Life Cycle  (0) 2021.10.13
JSX -> Basic  (0) 2021.10.13
Basic  (0) 2021.10.13