This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
7. implement debounce() with leading & trailing option
Here's one possible solution:
function debounce(func, delay, options = { leading: false, trailing: true }) {
let timeoutId
return function (...args) {
const callNow = options.leading && !timeoutId
clearTimeout(timeoutId)
timeoutId = setTimeout(() => {
if (options.trailing || callNow) {
func.apply(this, args)
}
timeoutId = null
}, delay)
if (callNow) {
func.apply(this, args)
}
}
}
In this implementation, we start by defining the timeoutId
variable to keep track of the current timeout. We return a function that calls func
after the specified delay
, unless the function is called again in the meantime. If leading
is true, we call func
immediately and then start the timeout. If trailing
is false, we don't call func
after the timeout expires, unless leading
is also true. We use apply
to call func
with the correct this
value and arguments.