AI solution for JavaScript Coding Question on BFE.dev
6. implement basic debounce()
Here's one possible implementation of debounce()
:
function debounce(func, delay) { let timerId; return function(...args) { if (timerId) { clearTimeout(timerId); } timerId = setTimeout(() => { func.apply(this, args); }, delay); };}
This implementation returns a new function that wraps the original function passed in as an argument. When the wrapped function is called, it first checks if there's an existing timer (i.e. a previous call to the wrapped function is already waiting to execute). If there is, it cancels the timer with clearTimeout()
. Then it sets a new timer with setTimeout()
to wait for the specified delay
. When the timer completes, the wrapped function is called with func.apply()
and any arguments that were passed to the wrapped function.
Note that this implementation doesn't handle edge cases like calling the wrapped function with null
or undefined
arguments, or returning values from the wrapped function. It also doesn't handle situations where the this
context of the wrapped function needs to be preserved. For a more robust implementation that covers these cases, it's probably best to use a third-party library like lodash.