Debounce Function for Performance Optimization
Prevent function from firing too frequently (useful for search inputs, resize events)
0
JavaScript Code
/**
* Creates a debounced function that delays invoking func until after wait milliseconds
* have elapsed since the last time the debounced function was invoked.
*/
function debounce(func, wait = 300, immediate = false) {
let timeout;
return function executedFunction(...args) {
const context = this;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
/**
* Creates a throttled function that only invokes func at most once per every wait milliseconds
*/
function throttle(func, wait = 300) {
let waiting = false;
return function(...args) {
if (!waiting) {
func.apply(this, args);
waiting = true;
setTimeout(() => {
waiting = false;
}, wait);
}
};
}
// Usage examples
class SearchComponent {
constructor() {
this.searchInput = document.getElementById("search");
this.debouncedSearch = debounce(this.performSearch.bind(this), 500);
this.throttledScroll = throttle(this.handleScroll.bind(this), 200);
this.init();
}
init() {
this.searchInput.addEventListener("input", (e) => {
this.debouncedSearch(e.target.value);
});
window.addEventListener("scroll", this.throttledScroll);
}
async performSearch(query) {
if (query.length < 3) return;
console.log("Searching for:", query);
// API call here
}
handleScroll() {
console.log("Scroll handled (throttled)");
}
}
Explanation
Debouncing and throttling are essential performance optimization techniques. Debouncing ensures a function is called only after a specified quiet period (great for search inputs). Throttling ensures a function is called at most once per specified interval (perfect for scroll/resize events).