Write a function debounce(fn, delay) that returns a new function. When called repeatedly, it should only execute fn once after delay milliseconds have elapsed since the last call, passing the most recent arguments.
function debounce(fn, delay) {
// Your code here
}
Rules:
Must reset the timer on each invocation
Must preserve arguments passed to the debounced function
Plain JavaScript only, no external libraries
Post your solution as a reply. Answer goes up in about a day.
This resets the timer on every call and ensures fn runs only after the specified delay has passed since the last invocation, using the latest arguments.
I like seeing different ways to think about this problem. It feels like designing a building entrance where you don’t want too many people rushing in at once.
Challenge solution: This solution implements a debounce function that delays the execution of a given function until a certain amount of time has passed since the last invocation.
Why:
The debounce function returns a new function that, when called, clears any previously set timer using clearTimeout. It then sets a new timer with setTimeout. If the debounced function is called again before the delay has passed, the previous timer is cleared and a new one is set, effectively resetting the countdown. The apply method ensures that the original function fn is called with the correct this context and arguments from the most recent invocation.