Debounce a function
You type react into a search box, and five requests go out — one per
keystroke. Four of them answer a question you have already moved past. Each one
costs a round trip, and the reply that lands last is not always the one for the
letters on screen.
The fix is to wait until you stop typing. Every call resets a timer, and the
wrapped function runs once that timer finally expires with no new call arriving.
That pattern is called debounce: a burst of rapid calls becomes a single call.
The shape is always the same. On each call you cancel the pending timer and schedule a fresh one:
function debounce(fn, wait) {
let timer;
return () => {
clearTimeout(timer);
timer = setTimeout(fn, wait);
};
}
Because timer lives in the closure returned by debounce, every call shares
the same timer and can cancel the previous one. The wrapped function runs at most
once per quiet period, wait milliseconds after the last call.
Export debounce from index.js. Your job is to schedule the wrapped function
once the burst ends, instead of running it on every call.
Challenge
A search box fires a request on every keystroke, so one word sends a pile of
calls that are already out of date. Export a debounce function from
index.js to collapse them into one.
debounce takes a function fn and a wait in milliseconds, and returns a new
function. Each call to the returned function cancels the previous timer and
schedules a fresh one, so fn runs wait milliseconds after the last call.
Call it several times in a row and fn runs exactly once.