Build an Advanced Debounce Function with Immediate and Cancel Options
Create a robust debounce utility function in JavaScript that delays invoking a function until after a specified wait time elapses since the last call. Support both immediate execution on the leading edge and the ability to cancel a pending invocation.
Challenge prompt
Write a function named debounce that accepts three parameters: a function func, a delay time in milliseconds wait, and an options object. The options object can have two boolean properties: 'immediate' and 'cancelable'. The debounce function should return a new debounced version of func with the following behavior: 1. When called repeatedly, the original func should only be invoked once, either after wait milliseconds have elapsed since the last call (trailing edge), or immediately if immediate is true (leading edge). 2. If immediate is true, the first call to the debounced function should invoke func immediately, then ignore subsequent calls until wait elapses. 3. If cancelable is true, the debounced function should have a method called cancel that can be called to cancel any pending invocation. Implement this debounce function fully so that it can be used to limit the rate at which a function runs, with flexible configuration for immediate triggers and canceling. Example usage: const debounced = debounce(() => console.log('Triggered!'), 1000, { immediate: true, cancelable: true }); debounced(); debounced.cancel(); // should cancel any scheduled call if exists
Guidance
- • Use a closure to store timing state between calls.
- • Use setTimeout and clearTimeout to manage the delay.
- • Implement the cancel method conditionally based on the options object.
Hints
- • Store a reference to the timeout ID so you can clear it.
- • To support immediate invocation, track if the function was already called within the wait period.
- • Attach the cancel method as a property of the returned function.
Starter code
function debounce(func, wait, options = {}) {
// Your implementation here
}Expected output
Upon calling debounced(), the func logs 'Triggered!' immediately if immediate is true; subsequent calls within wait ms do not invoke func. Calling debounced.cancel() stops any pending invocation representing no output afterward.
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.