Throttle a function
You attach a handler to scroll to update a reading position. The browser fires
scroll dozens of times a second, so the handler runs on every pixel and the page
starts to drag. Most of those calls are wasted — the position only needs to catch
up now and then.
The fix is to run the handler at most once per window. The first call goes through
immediately, then every call for the next wait milliseconds is ignored. Where
debounce waits for the burst to stop, throttle holds a steady rate. That
pattern is called throttle.
The shape keeps two things in a closure: the function to run and the timestamp of the last call. On each call you compare the current time to that timestamp and only run when enough time has elapsed:
function throttle(fn, wait) {
let last = 0;
return () => {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn();
}
};
}
The first call sees last at 0, so now - last clears wait and fn runs
immediately. Every later call inside the window is skipped because now - last
is too small. Once wait milliseconds have gone by, the next call runs and the
window resets.
Export throttle from index.js. Your job is to make it run the wrapped
function at most once per wait milliseconds.
Challenge
A page that updates a reading position on every scroll event runs its handler
dozens of times a second, and most of those calls are wasted. Export a throttle
function from index.js to run it at a steady rate instead.
throttle takes a function fn and a wait in milliseconds, and returns a new
function. The first call to the returned function runs fn immediately; any
further calls within wait milliseconds are ignored. Call it several times in a
row and fn runs exactly once, and only after wait milliseconds may the next
call run it again.