Throttle, Debounce

song·2024년 1월 21일
0

js 정보

목록 보기
29/30
post-thumbnail

Throttle, Debounce는 애니메이션 성능을 고려해서 필수 개념

: 자주 사용되는 이벤트, 함수들의 실행 빈도를 줄여 성능 향상시킴

ex) input으로 입력할 때마다 api로 데이터를 가져온다면 성능↓

해결법

  • 일정 시간을 두고 데이터 가져오기 (Throttle)
  • 입력이 끝난 후 데이터 가져오기 (Debounce)


Throttle

: 입력 주기를 방해하지 않고, 일정 시간 동안의 입력을 모아 정해진 시간마다 이벤트를 호출



Debounce

: 입력 주기가 끝남과 동시에 이벤트를 호출

<input type="text" class="inp" />

<div>
  <span>Debounce: </span>
  <span class="text"></span>
</div>
const inp = document.querySelector('.inp');
const text = document.querySelector('.text');


function debounce(callback, delay = 1000) {
  let timeout;

  return (...args) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      callback(...args);
    }, delay);
  }
}

const inputText = debounce(val => {
  text.textContent = val
})

inp.addEventListener('input', e => {
  inputText(e.target.value);
});



profile
인간은 적응의 동물

0개의 댓글

관련 채용 정보