This solution is generated by ChatGPT, correctness is not guaranteed. You might also be able to find a solution fromcommunity postsor official solution page.
AI solution for JavaScript Coding Question on BFE.dev
5. implement throttle() with leading & trailing option
function throttle(func, delay, options) { let lastCallTime, timer, leadingCalled const { leading = true, trailing = true } = options || {} return function throttledFunction(...args) { const now = new Date().getTime() if (!lastCallTime && leading) { leadingCalled = true func.apply(this, args) lastCallTime = now } else { clearTimeout(timer) timer = setTimeout(() => { if (trailing || (now - lastCallTime >= delay)) { func.apply(this, args) lastCallTime = now } }, delay - (now - lastCallTime)) } if (leading && leadingCalled) leadingCalled = false }}
Explanation:
- The
throttlefunction accepts three arguments: thefuncto be throttled, thedelaybetween two consecutive calls offunc, and an optionaloptionsobject withleadingandtrailingproperties to control whether to invoke the function immediately and after waiting, respectively. - Inside
throttle, we declarelastCallTime,timer, andleadingCalledvariables to keep track of the previous invocation time, the current timeout timer, and whether thefunchas been called with the leading option, respectively. - We then return the
throttledFunction, which accepts any number of arguments (...args) to be passed tofunc. - Inside
throttledFunction, we get the current timestamp in milliseconds (now). - If
lastCallTimeis falsy (i.e., this is the first invocation) andleadingis true, we setleadingCalledto true, invokefuncwiththiscontext andargs, and updatelastCallTimewithnow. - Otherwise, we clear the previous timeout timer
timer(if any), and set a new timer usingsetTimeoutwith a callback function that checks iftrailingis true or if thedelaybetween the current and previous invocations has passed. If so, we invokefuncwiththiscontext andargs, and updatelastCallTimewithnow. Otherwise, we wait for the remaining time ofdelay - (now - lastCallTime)before invokingfunc. - Finally, if this call is with
leadingoption andfunchas already been called, we setleadingCalledto false to prevent callingfuncagain in the future.