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
throttle
function accepts three arguments: thefunc
to be throttled, thedelay
between two consecutive calls offunc
, and an optionaloptions
object withleading
andtrailing
properties to control whether to invoke the function immediately and after waiting, respectively. - Inside
throttle
, we declarelastCallTime
,timer
, andleadingCalled
variables to keep track of the previous invocation time, the current timeout timer, and whether thefunc
has 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
lastCallTime
is falsy (i.e., this is the first invocation) andleading
is true, we setleadingCalled
to true, invokefunc
withthis
context andargs
, and updatelastCallTime
withnow
. - Otherwise, we clear the previous timeout timer
timer
(if any), and set a new timer usingsetTimeout
with a callback function that checks iftrailing
is true or if thedelay
between the current and previous invocations has passed. If so, we invokefunc
withthis
context andargs
, and updatelastCallTime
withnow
. Otherwise, we wait for the remaining time ofdelay - (now - lastCallTime)
before invokingfunc
. - Finally, if this call is with
leading
option andfunc
has already been called, we setleadingCalled
to false to prevent callingfunc
again in the future.