Implement a debounced function (with leading option)
Grayswan AiSoftware Engineer · Technical ScreenLast updated
This problem tests your understanding of higher-order functions, closure scope, and asynchronous execution control by requiring the implementation of a flexible debounce utility.
Debounce Utility
Implement a function debounce(func, wait, options) that returns a debounced version of the input function.
Requirements
- The returned function should delay the execution of
funcuntilwaitmilliseconds have elapsed since the last time it was invoked. - The
optionsobject should support aleadingboolean flag. Ifleadingistrue, the function should be executed immediately on the first call rather than waiting for the delay period to expire. - The function must preserve
thiscontext and correctly pass all arguments to the underlyingfunc. - If multiple calls occur during the
waitwindow, only the latest arguments should be used for any trailing execution.
Signature
function debounce(func, wait, options = { leading: false }) {
// Implementation goes here
}
Examples
Example 1: Trailing edge (default)
const log = debounce((msg) => console.log(msg), 1000);
log('A');
log('B'); // 'A' is cancelled, 'B' will execute after 1s
Example 2: Leading edge
const log = debounce((msg) => console.log(msg), 1000, { leading: true });
log('A'); // 'A' executes immediately
log('B'); // 'B' is ignored because it's within the 1s window
Constraints
waitis a non-negative integer.- Ensure the implementation handles rapid consecutive calls efficiently.
Hints
Hint 1
Use a variable to store the timer ID returned by `setTimeout` to track and clear pending executions.
Hint 2
For the leading edge, check if the timer is null and execute immediately, then prevent subsequent calls until the wait duration passes.
Hint 3
Ensure you use `.apply(this, arguments)` to correctly forward the function context and input parameters to the wrapped function.
Follow-up questions
- How would you add a 'cancel' method to the returned function to clear any pending execution?
- How does this implementation change if we want to support a 'maxWait' option that forces execution if the debounced function is called repeatedly over a long period?
- How would you unit test this function to ensure it doesn't trigger unexpectedly in a high-frequency event environment?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.