Debounce a function with added cancel and flush methods
Implement a JavaScript utility called debounce that enhances the control over function executions in response to rapid or repeated triggers. This utility should accept two parameters: a target function (func) and a wait time in milliseconds (wait). The debounce function returns a new, debounced version of the target function that ensures it is only executed after the specified wait time has elapsed since its last invocation. Lodash’s debounce exposes the same API, so a debounce with cancel and flush should feel familiar.
If the debounced function is called again before the wait time has expired, the countdown is reset, delaying the function’s execution until the wait time passes without any further invocations. This behavior is crucial in scenarios such as handling rapid user inputs, window resizing, or scroll events, where controlling the rate of function execution can significantly enhance performance and user experience.
In addition to the basic debouncing behavior, the returned function includes two methods for added flexibility:
This advanced debouncing mechanism, with its cancel and flush capabilities, provides a powerful tool for optimizing dynamic function execution in response to user actions or system events.