CodeNot attempted
Throttle (leading + trailing)
Difficulty: medium
Let fn run at most once per wait ms, like lodash's default.
- the first call runs immediately (leading)
- calls during the window collapse; when the window ends
fnruns once more with the latest args (trailing), which opens a new window - if nothing was called during the window, nothing runs at its end
Follow-up: when would you choose throttle over debounce? (scroll position vs search box)
Show reference solution
export function throttle<A extends unknown[]>(fn: (...args: A) => void, wait: number): (...args: A) => void { let timer: ReturnType<typeof setTimeout> | undefined; let lastArgs: A | undefined; // the latest call made while waiting let lastThis: unknown;
function endWindow() { if (lastArgs) { // Run the trailing call, which starts a new window. fn.apply(lastThis, lastArgs); lastArgs = undefined; timer = setTimeout(endWindow, wait); } else { timer = undefined; } }
return function (this: unknown, ...args: A) { if (timer) { lastArgs = args; lastThis = this; return; } fn.apply(this, args); // leading call timer = setTimeout(endWindow, wait); };}
Ctrl Enter