Implementing a Simple Debounce
You'll learn how to write a basic debounce function that delays execution until a pause in rapid-fire events.
Now that you understand what debounce solves (preventing function spam during rapid events like typing or scrolling), let's build one from scratch.
The core mechanic is simple: each time the debounced function is called, cancel any pending execution and schedule a new one after a delay. If calls keep coming, the timer keeps resetting. Only when calls stop does the function finally run.
The Basic Implementation
function debounce(func, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId); // Cancel previous timer
timeoutId = setTimeout(() => {
func(...args); // Execute after delay
}, delay);
};
}
How It Works
debouncereturns a new wrapper function- Each call to the wrapper clears the previous
setTimeoutwithclearTimeout - A fresh timer is started with
setTimeout - If no new call happens within
delaymilliseconds,funcfinally executes
Using It
const saveInput = (value) => {
console.log('Saving:', value);
};
const debouncedSave = debounce(saveInput, 500);
// Simulate rapid typing
debouncedSave('H');
debouncedSave('He');
debouncedSave('Hel');
debouncedSave('Hell');
debouncedSave('Hello'); // Only this triggers saveInput after 500ms pause
The function only executes once, 500ms after the last call. Perfect for search boxes or resize handlers!
Key Takeaway: A basic debounce uses setTimeout and clearTimeout to ensure a function only runs after a specified quiet period, resetting the timer on each call.