JavaScript
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
By EZ4Code Team
functionperformancedebounce
Code
function debounce(fn, delay = 300, immediate = false) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
if (immediate && !timer) {
fn.apply(this, args);
}
timer = setTimeout(() => {
timer = null;
if (!immediate) fn.apply(this, args);
}, delay);
};
}Explanation
Debounce is suitable for high-frequency scenarios like search input and window resize, avoiding frequent execution.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Throttle Function
Limit a function to execute at most once within a time interval.
Promise.all Concurrency Control
A Promise executor with concurrency limit.
async/await Error Handling
Wrap async functions to uniformly catch exceptions.