TIL-68 Javascript 디바운싱과 쓰로틀링

PRB·2022년 3월 31일
0

JavaScript

목록 보기
23/24
post-thumbnail

디바운싱 (Debouncing)

연이어 호출되는 함수들 중 마지막 함수(또는 제일 처음)만 호출하도록 하는 것

대표적으로 ajax 검색에 자주 쓰인다.

<input id="input" />

document.querySelector('#input').addEventListener('input', function(e) {
  console.log('ajax 요청', e.target.value);
});

예를 들면 이런 로직이 있다고 했을때 타자하나하마다 콘솔이 찍힐것이다. 그말은 누를때마다 통신을 요청한다는 것이다. 그렇게될경우 필요없는 서버 비용이 나오것이다. 그럴때 디바운싱을 사용하면된다.

let timer;
document.querySelector('#input').addEventListener('input', function(e) {
  if (timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(function() {
    console.log('ajax 요청', e.target.value);
  }, 200);
});

200ms동안 입력이 없으면 입력이 끝난 것으로 친다.

쓰로틀링(Throttling)

마지막 함수가 호출된 후 일정 시간이 지나기 전에 다시 호출되지 않도록 하는 것

쓰로틀링은 스크롤을 올리거나 내릴 때 보통 사용한다.
스크롤을 올리거나 내릴 때 scroll 이벤트가 매우 많이 발생한다.
몇 초에 한 번, 또는 몇 밀리초에 한 번씩만 실행되게 제한을 두면 된다.

let timer;
document.querySelector('#input').addEventListener('input', function (e) {
  if (!timer) {
    timer = setTimeout(function() {
      timer = null;
      console.log('ajax 요청', e.target.value);
    }, 200);
  }
});

출처 : https://www.zerocho.com/category/JavaScript/post/59a8e9cb15ac0000182794fa

profile
사용자 입장에서 사용자가 원하는 것을 개발하는 프론트엔드 개발자입니다.

0개의 댓글