Both limit how often a function runs for events that fire very fast, like typing or scrolling.
| Technique | Runs | Good for |
|---|
| Debounce | Once, after the events stop for some time | Search box suggestions, resize |
| Throttle | At most once in every interval | Scroll and mouse move handlers |
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
input.addEventListener("input", debounce(search, 300));
The debounced function runs only 300 ms after the last key press. It uses a closure to remember the timer.
Learn more about the similar topics:
| Tutorials |
| No Content Found. |
| Exercises & Assignments |
| No Content Found. |
| Interview Questions & Answers |
| No Content Found. |