Debounce와 Throttling은 잦은 이벤트 발생에 따른 성능 이슈를 완화하는데 쓰인다.
De + bounce 튀지 않는다. -> 주기, 간격이 없다. -> 제일 끝 이벤트만 처리.
function debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// 사용 예제
const handleSearch = debounce((query) => {
console.log('검색 요청:', query);
}, 300);
쓰이는 예시 : 사용자 입력 처리
throttle 자동차 조절판 -> 일정 간격으로 나눠져 있음 -> 일정 간격으로 이벤트 처리.
function throttle(func, limit) {
let lastFunc;
let lastRan;
return function(...args) {
const context = this;
if (!lastRan) {
func.apply(context, args);
lastRan = Date.now();
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
// 사용 예제
const handleScroll = throttle(() => {
console.log('스크롤 이벤트 처리');
}, 200);
쓰이는 예시 : 스크롤
👁🗨