Katkat

Implement a debounced function (with leading option)

Grayswan AiSoftware Engineer · Technical Screen

Last 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 func until wait milliseconds have elapsed since the last time it was invoked.
  • The options object should support a leading boolean flag. If leading is true, the function should be executed immediately on the first call rather than waiting for the delay period to expire.
  • The function must preserve this context and correctly pass all arguments to the underlying func.
  • If multiple calls occur during the wait window, 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

  • wait is 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?