We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
A medium frontend problem, graded against 5 test cases (2 of them hidden).
React and browser-platform problems - hooks, event handling, and rendering behaviour.
Reach for it when you see: A component, hook, or DOM-behaviour question rather than an algorithm.
More Frontendproblems →```js
function throttle(fn, interval) {
let lastFire = -Infinity;
return function (...args) {
const now = Date.now();
if (now - lastFire >= interval) {
lastFire = now;
fn.apply(this, args);
}
// else drop
};
}
```
Variants worth knowing:
- Trailing edge: ignore the first call, fire the last call after `interval` of silence (this is debounce, not throttle).
- Leading + trailing: fire immediately AND fire once at the end of the window if any calls were dropped (the lodash default).
- Sliding window vs fixed window: the implementation above is "fixed window from last fire". A sliding-window throttle would maintain a queue.
Throttle vs debounce - the canonical question:
- Throttle: "max N calls per second". Fires steadily during a continuous stream. Good for scroll, mousemove, window-resize - things you want updated periodically.
- Debounce: "wait for silence". Only fires when the input stops. Good for search-as-you-type, autosave, expensive validations.
`requestAnimationFrame` as a throttle for animations: `requestAnimationFrame(fn)` runs once per repaint (~60fps), naturally throttling visual updates. Better than `setTimeout(fn, 16)` because it pauses on backgrounded tabs.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
Read off this problem's own test suite, so these are the cases a submission actually has to survive.
These apply to the pattern as a whole, not just this problem.