function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
const searchInput = document.getElementById('searchInput');
searchInput.addEventListener('input', debounce((event) => {
console.log('Search query:', event.target.value);
}, 500));
function throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
window.addEventListener('scroll', throttle(() => {
console.log('Scroll event');
}, 1000));
이 바닐라 자바스크립트 예제들을 통해 디바운싱과 쓰로틀링을 구현하고 활용하는 방법을 이해할 수 있습니다. 외부 라이브러리 없이도 간단하게 이벤트 핸들링을 최적화할 수 있습니다.