Write a function `throttle(fn, limit)` that returns a throttled version. It should invoke `fn` at most once per `limit` ms.
Problem Statement
Write a function `throttle(fn, limit)` that returns a throttled version. It should invoke `fn` at most once per `limit` ms.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Throttling limits how often a function can execute.
š” Hint 2:
Track the last execution time and only call if enough time has passed.
š” Hint 3:
Use a flag or timestamp to prevent calls within the limit window.
ā
Solution:
```javascript
function throttle(fn, limit) {
let inThrottle = false;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
```