Problem
Implement throttle(fn, limit) that returns a throttled wrapper around fn.
The wrapper must ensure fn runs at most once every limit milliseconds, even if the wrapper is called many times in that window.
Common uses: scroll handlers, mousemove, rate-limiting API calls.
Input
let count = 0;
const onScroll = throttle(() => {
count++;
}, 100);
onScroll();
onScroll();
onScroll();
// only the first call runs immediately; others within 100ms are ignored
Expected output
- Immediately after the three calls:
count === 1 - After waiting 100ms and calling once more:
count === 2
Implement from scratch:
function throttle(fn, limit) {
// Your code here
}