Debouncing and throttling are two techniques used in JavaScript to limit the rate at which a function is executed. They can enhance performance and improve the user experience by reducing the frequency of function calls during events like scrolling or resizing.
The debounce function ensures that a function is only executed once after a specified delay, regardless of how many times it is triggered within that delay.
function debounce(func, delay) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
// Example usage
const logResize = debounce(() => {
console.log('Window resized!');
}, 500);
window.addEventListener('resize', logResize);
The throttle function limits the execution of a function to a fixed interval, ensuring that it cannot be called again until the specified time has passed.
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(() => {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, Math.max(limit - (Date.now() - lastRan), 0));
}
};
}
// Example usage
const logScroll = throttle(() => {
console.log('Window scrolled!');
}, 1000);
window.addEventListener('scroll', logScroll);
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?