This solution is generated by ChatGPT, correctness is not guaranteed.
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 immediately
throttledLog(2); // is ignored
throttledLog(3); // is ignored
setTimeout(() => throttledLog(4), 500); // logs 4 after 500ms
setTimeout(() => throttledLog(5), 1000); // logs 5 after 1000ms