✨
Snippets
JavaScript Snippet: Debounce and Throttle
By Mohd Baquir
Qureshi
•
If you are handling window scrolling, resizing, or search inputs, you need these functions. Running logic on every single keystroke or scroll tick will destroy browser performance.
Debounce
Debounce ensures a function is only executed after a user stops an action for a certain amount of time. Perfect for search bars.
function debounce(func, delay) {
let timeoutId;
return function (...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
// Usage:
const searchInput = document.getElementById('search');
searchInput.addEventListener('input', debounce((e) => {
console.log('Fetching results for:', e.target.value);
}, 300));
Throttle
Throttle ensures a function is executed at a regular interval during a continuous action. Perfect for scroll tracking or window resizing.
function throttle(func, limit) {
let inThrottle;
return function (...args) {
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
// Usage:
window.addEventListener('scroll', throttle(() => {
console.log('Scroll position:', window.scrollY);
}, 200));