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
4. implement basic throttle()
Here's one possible implementation of a basic throttle()
function in JavaScript:
function throttle(func, delay) { let cooling = false; let lastArgs = null; return function(...args) { if (!cooling) { cooling = true; func.apply(this, args); setTimeout(() => cooling = false, delay); } else { lastArgs = args; } };}
This implementation creates a closure around cooling
, lastArgs
, func
, and delay
. The returned function is the throttled version of func
.
On each invocation of the throttled function, it checks whether it's in a "cooling" state. If not, it immediately calls func
with the provided arguments and sets a timeout to reset the cooling state after delay
milliseconds.
If the function is in a cooling state, it simply saves the arguments for later use. Note that this implementation always returns undefined
, which means some calls to func
might be silently dropped.
Here's how you could use it:
const throttledLog = throttle(console.log, 1000);throttledLog(1); // logs 1 immediatelythrottledLog(2); // is ignoredthrottledLog(3); // is ignoredsetTimeout(() => throttledLog(4), 500); // logs 4 after 500mssetTimeout(() => throttledLog(5), 1000); // logs 5 after 1000ms