JavaScript Debounce Function
When a visitor types in a search box, the input event fires on every key. Calling the server for each letter is wasteful. A debounce function waits until the visitor has stopped typing for a short time, and then runs once.
Debounce function
function debounce(fn, delay = 300) {
let timer;
return function (...args) {
clearTimeout(timer); // cancel the previous call
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
Use it
function search(text) {
console.log("Searching for: " + text);
}
const debouncedSearch = debounce(search, 300);
// fast calls, like fast typing
debouncedSearch("j");
debouncedSearch("ja");
debouncedSearch("jav");
Only the last call runs, 300 ms after it:
Tutorials Class - Output Window
Searching for: jav
With a real input box:
input.addEventListener("input", (e) => debouncedSearch(e.target.value));
How it works
- Every call clears the old timer and starts a new one.
- The function runs only when no new call comes for
delaymilliseconds. - The timer is kept in a closure, so each debounced function has its own timer.
If you need to run the function at regular intervals while events keep coming (like scroll), you need a throttle. Read debounce vs throttle.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |