This is a card in Dave's Virtual Box of Cards.
Debouncing JavaScript input
Created: 2024-08-04
back to javascript
You don’t need a big utility library to debounce input. JS has a reset-able timer mechanism. Here’s a handy function:
function debounce(f, ms){
var t; // Scope to this invocation
return function(){
clearTimeout(t);
t = setTimeout(f, ms);
};
}
And here’s an example of use:
function update(){ ... };
// Debounce the "update()" function so it isn't called until
// there's a 1 second pause in a textarea's input (typing).
my_textarea.addEventListener('input',
debounce(update, 1000)
);
Here’s a full working example: debounce.html