
🖋️ Debounce 와 Throttle 의 단순 비교
Debounce이벤트가 발생하여 Delay 끝나기 전에 다시 이벤트가
트리거 되면 Delay 타이머 재설정 (반복)
더이상 이벤트가 발생하지 않으면 최종적으로 함수 실행
Delay 내에 이벤트가 계속 트리거 되면 함수 실행은
무기한 연기될 수 있음
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// Example usage:
const handleInput = debounce(() => console.log('Input handled'), 500);
window.addEventListener('input', handleInput);
Throttle이벤트 발생, 함수는 첫 이벤트 트리거 시 즉시 실행
실행 후 후속 이벤트가 기능을 트리거하지 못하게
쿨다운 기간 시작, 쿨다운 기간이 종료되면 다시 이벤트 트리거 OK
이벤트가 계속해서 트리거 되면 함수는 지정된 쿨다운 기간보다
자주 실행되지 않지만 실행은 보장
function throttle(func, limit) {
let inThrottle;
return function executedFunction(...args) {
if (!inThrottle) {
func(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
// Example usage:
const handleScroll = throttle(() => console.log('Scroll handled'), 500);
window.addEventListener('scroll', handleScroll);
디바운스스로틀Debounce를 사용하면 검색창에 입력을 완료하는 등 작업이 완료되거나 일시 중지된 후에 함수가 실행되도록 해야 합니다.
Throttle은 스크롤이나 크기 조정 이벤트 처리와 같이 브라우저나 서버에 과부하가 걸리는 것을 방지하기 위해 함수가 일관된 속도로 실행되도록 해야 할 때 사용합니다.