π Debounce
Debounce delays the function until the user stops doing something.
If more events come in before the delay ends, the timer resets.
β Best when you want the final action.
Examples:
- Auto-saving form input (save when the user stops typing)
- Searching-as-you-type queries
- Validating input fields
Debounce Example
1function debounce(fn, delay) {
2 let timer;
3 return function (...args) {
4 clearTimeout(timer);
5 timer = setTimeout(() => fn.apply(this, args), delay);
6 };
7}
8
9// Usage: auto-save after user stops typing for 500ms
10const autoSave = debounce(() => {
11 console.log("Auto-saving...");
12}, 500);
13
14document.querySelector("input").addEventListener("input", autoSave);
15
1function debounce(fn, delay) {
2 let timer;
3 return function (...args) {
4 clearTimeout(timer);
5 timer = setTimeout(() => fn.apply(this, args), delay);
6 };
7}
8
9// Usage: auto-save after user stops typing for 500ms
10const autoSave = debounce(() => {
11 console.log("Auto-saving...");
12}, 500);
13
14document.querySelector("input").addEventListener("input", autoSave);
15
Behavior:
If the user types continuously, the save function won't run until they pause for 500ms.
π Throttle
Throttle ensures the function executes at MOST once every X milliseconds, no matter how many events occur.
β Best when events fire continuously and you want updates at controlled intervals.
Examples:
- Window resize handler
- Scroll position updates
- Drag events
- Mouse movement tracking
Throttle Example
1function throttle(fn, limit) {
2 let inThrottle = false;
3 return function (...args) {
4 if (!inThrottle) {
5 fn.apply(this, args);
6 inThrottle = true;
7 setTimeout(() => (inThrottle = false), limit);
8 }
9 };
10}
11
12// Usage: handle resize event at most once every 200ms
13const handleResize = throttle(() => {
14 console.log("Resized:", window.innerWidth);
15}, 200);
16
17window.addEventListener("resize", handleResize);
18
1function throttle(fn, limit) {
2 let inThrottle = false;
3 return function (...args) {
4 if (!inThrottle) {
5 fn.apply(this, args);
6 inThrottle = true;
7 setTimeout(() => (inThrottle = false), limit);
8 }
9 };
10}
11
12// Usage: handle resize event at most once every 200ms
13const handleResize = throttle(() => {
14 console.log("Resized:", window.innerWidth);
15}, 200);
16
17window.addEventListener("resize", handleResize);
18
Behavior:
Even if the browser fires 200 resize events in 1 second, the handler only runs once every 200ms.
π Which one to use?
1οΈβ£ Auto-saving form input β Use DEBOUNCE
Why?
You donβt want to save on every keystroke, only when the user pauses typing.
2οΈβ£ Handling window resize β Use THROTTLE
Why?
Resize fires rapidly. You want updates at a controlled rate, not only after resize stops.