Write a function `debounce(fn, delay)` that returns a debounced version. It should only invoke `fn` after `delay` ms of inactivity. Return the debounced function.
Problem Statement
Write a function `debounce(fn, delay)` that returns a debounced version. It should only invoke `fn` after `delay` ms of inactivity. Return the debounced function.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Debouncing delays execution until a pause in calls.
š” Hint 2:
Clear the previous timer on each call and set a new one.
š” Hint 3:
let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); };
ā
Solution:
```javascript
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
```