JavaScript Debounce Function for Performance Optimization
Description
This JavaScript snippet implements a versatile `debounce` function, crucial for optimizing performance in web applications. It limits the rate at which a function can fire, preventing excessive calls during rapid events like typing, scrolling, or window resizing. The function executes only after a specified `wait` period has passed without further invocations, with an optional `immediate` flag to trigger on the leading edge.
Code Snippet
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge instead of the trailing.
*
* @param {Function} func The function to debounce.
* @param {number} wait The number of milliseconds to wait.
* @param {boolean} immediate If true, trigger the function on the leading edge.
* @returns {Function} The debounced function.
*/
function debounce(func, wait, immediate) {
let timeout;
let result;
return function() {
const context = this;
const args = arguments;
const later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
}
// --- Example Usage ---
// Simulate an input field where user is typing
const myInput = document.createElement('input');
myInput.placeholder = "Type here to see debounce in action...";
document.body.appendChild(myInput);
const logChange = function(value) {
console.log("API Call/Heavy Operation with:", value);
};
// Create a debounced version of logChange
const debouncedLogChange = debounce(logChange, 500); // Wait 500ms after user stops typing
myInput.addEventListener('keyup', (event) => {
debouncedLogChange(event.target.value);
});
console.log("Type something in the input field above. The console log will appear 500ms after you stop typing.");