Build an Optimized Debounced Function Creator in JavaScript
Create a higher-order function that returns a debounced version of a given input function, ensuring optimized invocation timing and immediate execution control.
Challenge prompt
Write a function named 'createDebouncedFunction' that accepts two parameters: a callback function 'fn' and a delay time in milliseconds 'delay'. It should return a new function that when called, delays the invocation of 'fn' until after 'delay' milliseconds have elapsed since the last time the returned function was called. Additionally, this returned function should have two methods attached: 'cancel' to cancel any pending invocation, and 'flush' to immediately invoke the delayed function if pending. Ensure the implementation handles the context and arguments correctly when invoking 'fn'.
Guidance
- • Use closures to keep track of the timer and ensure that multiple calls reset the timer correctly.
- • Attach 'cancel' and 'flush' methods as properties of the returned debounced function for external control.
- • Preserve the 'this' context and arguments when invoking the original callback function.
Hints
- • Use 'setTimeout' and 'clearTimeout' to implement the delay functionality.
- • Store the timer id in a variable scoped inside 'createDebouncedFunction'.
- • Use 'apply' or 'call' to invoke 'fn' with proper context and arguments.
Starter code
function createDebouncedFunction(fn, delay) {
// Your code here
}Expected output
const debounced = createDebouncedFunction(console.log, 1000); debounced('Hello'); // If no new calls happen within 1000ms, logs: Hello // debounced.cancel() cancels pending call // debounced.flush() immediately calls the pending invocation
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.