In web development, debouncing and throttling are techniques used to limit the rate at which a function can fire. They are particularly useful for optimizing performance in event-heavy scenarios like scrolling and resizing.
Debouncing ensures that a function is only called after a certain period of inactivity. For example, debouncing is often used on input fields to avoid sending requests until the user has stopped typing for a specified duration.
Throttling, on the other hand, limits the number of times a function can be called over time. This is useful for events that trigger frequently, such as scrolling or resizing.
Below is an example of how to implement debouncing and throttling in jQuery:
$(document).ready(function() {
// Debounce function
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
// Throttle function
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();
}
}, limit - (Date.now() - lastRan));
}
};
}
// Apply debouncing to keyup event
$('#inputField').on('keyup', debounce(function() {
console.log('Input value:', $(this).val());
}, 300));
// Apply throttling to scroll event
$(window).on('scroll', throttle(function() {
console.log('Scroll event triggered');
}, 1000));
});
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?