Implement debounce
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Implement debounce(func, wait). It returns a new function that delays calling func until wait milliseconds have passed since the last time the debounced function was called.
Debouncing is how you stop a search box from sending a request on every keystroke, or a resize handler from running hundreds of times a second: only the final call in a burst gets through.
let i = 0
const increment = () => i++
const debounced = debounce(increment, 100)
// t = 0
debounced()
// i is still 0
// t = 50: a new call restarts the 100ms wait
debounced()
// t = 150: 100ms have passed since the last call
// i is now 1Requirements
debouncereturns a function, and calling it does not callfuncright away.funcis called once,waitms after the most recent call. Every new call restarts the wait.funcreceives the arguments of the latest call.funcruns with the samethisthe debounced function was called with.- Each debounced function has its own timer.
Note
You don't need to support the leading, maxWait or cancel options that Lodash's debounce has.
Approach
The debounced function needs to remember one thing between calls: the pending timer. A closure gives each debounced function its own private timeoutId.
On every call:
- Cancel the pending timer with
clearTimeout, if there is one. This is what "restarts the wait". - Start a new timer for
waitms that callsfunc.
Because only the last timer survives a burst, func runs once, with the arguments of the last call.
Keeping this and the arguments
Two details are easy to get wrong:
- Arguments: collect them with rest parameters (
...args) and pass them on withfunc.apply. this: the debounced function must be a regularfunction, not an arrow function, so it receives the caller'sthis. The timer callback, on the other hand, should be an arrow function, so it captures thatthislexically. With a regular callback,thisinside it would beundefined(orglobalThis).
Complexity
Each call is O(1) time. Memory is O(1) per debounced function: one timer id plus the latest arguments held by the pending callback.
Follow-ups interviewers ask
cancel()andflush(): attach methods to the returned function that clear the timer, or run the pending call right away.- Leading edge: call
funcon the first call of a burst instead of the last. - Debounce vs. throttle: throttle guarantees at most one call per interval during a burst; debounce waits for the burst to end.
Reference solution
/**
* @param {Function} func
* @param {number} wait
* @returns {Function}
*/
export default function debounce(func, wait) {
let timeoutId = null
return function debounced(...args) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
timeoutId = null
func.apply(this, args)
}, wait)
}
}export default function debounce<Args extends unknown[]>(
func: (this: unknown, ...args: Args) => void,
wait: number,
): (this: unknown, ...args: Args) => void {
let timeoutId: ReturnType<typeof setTimeout> | undefined
return function debounced(this: unknown, ...args: Args) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
timeoutId = undefined
func.apply(this, args)
}, wait)
}
}