TIL-68 Javascript 디바운싱과 쓰로틀링
디바운싱 (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
Author And Source
이 문제에 관하여(TIL-68 Javascript 디바운싱과 쓰로틀링), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@ssxst31/Javascript-디바운싱과-쓰로틀링저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)