Debouncing and throttling are techniques used to control how often a function is executed in response to events in JavaScript. Both are commonly used to improve performance, avoid excessive function calls, and enhance user experience in web applications.
Debouncing is a technique that ensures a function is only executed after a certain period of inactivity. It is particularly useful in situations where you want to limit the number of times a function (like an API call) is called in a short period, such as during typing in a text box or resizing a window.
function debounce(func, delay) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
};
}
const processInput = debounce(() => {
console.log('Input processed');
}, 300);
Throttling, on the other hand, ensures that a function is not called more than once in a specified amount of time. This is useful for events that fire in quick succession, like scrolling, where you may only want to react to the event at a set frequency.
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(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
}
const logScroll = throttle(() => {
console.log('Scroll event processed');
}, 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?