Debounce
Prompt
Debouncing is a method of preventing a function from being invoked too often, and instead waiting a certain amount of time until it was last called before invoking it. A great example of where this is useful is an auto-completing input field that calls an API with the partial input to get a list possible complete inputs.
In the example above, without debouncing, the API would be called when the user presses 'u' and return every country beginning with 'u'. However, the user would probably have already typed 'n' and 'i' before the server responds, and would naively try to make another two requests. As the responses come in, the list of suggestions below the input would quickly flash between different lists.
Instead, we can 'debounce' the request function: we would pass the request function to a 'debounce' function along with an interval value, and it would provide us with a debounced request function. Every time we call that function now, it would wait for the specified interval: if it is called again within that time, the interval would reset. If it is not called again, the original request function would finally be called.
In our 'Country' input above, with a debounced API request we would not see a request being made until the user stopped typing, making for a much smoother user experience. You should implement a 'debounce' function that accepts a callback and an interval, and returns a debounced version of the callback.
function debounce(callback, interval) {
// add your code here
}
const myCallback = () => console.log("Hello");
const myDebouncedCallback = debounce(myCallback, 1000);
// call function immediately (after 0ms)
myDebouncedCallback();
// call function after 100ms
setTimeout(myDebouncedCallback, 100);
// call function after 500ms
setTimeout(myDebouncedCallback, 500);
// call function after 2000ms
setTimeout(myDebouncedCallback, 2000);
// call function after 4000ms
setTimeout(myDebouncedCallback, 4000);
In the example above, the calls at 0ms and 100ms should be debounced, meaning they will not fire the console.log
due to a subsequent call within 1000ms, resetting the debounce interval. The calls at 500ms, 2000ms, and 4000ms should result in a console.log, since more than 1000ms passes after the call without another invocation.
Requirements
- The
debounce
function should accept acallback
and debounceinterval
- The
debounce
function should return a function that, when invoked multiple times, only invokes thecallback
once within theinterval
- The
debounce
function should throw an error if not passed a function in thecallback
param - The
debounce
function should throw an error if passed an invalidinterval
, e.g. not a number, <0 milliseconds
Submitting solutions
- Create a solution by forking one of our CodePen templates:
- Submit your solution here