Coding Challenge Practice - Question 117
Source: Dev.to
Problem Description
Implement an enhanced debounce function that supports options to invoke the wrapped function immediately (leading) or after a delay (trailing).
Solution Overview
-
State variables
timer: holds the current timeout identifier.lastArgs/lastThis: store the most recent arguments and context.
-
When the debounced function is called
- Save the arguments and
thiscontext. - Determine if the function should be called immediately (
option.leading && !timer). - Clear any existing timer.
- Set a new timer that, after
waitmilliseconds, will invoke the original function ifoption.trailingis enabled and there are pending arguments.
- Save the arguments and
-
Immediate execution
- If
shouldCallNowis true, invoke the original function right away and reset stored arguments.
- If
Code
function debounce(func, wait, option = { leading: false, trailing: true }) {
let timer = null;
let lastArgs;
let lastThis;
return function (...args) {
lastArgs = args;
lastThis = this;
const shouldCallNow = option.leading && !timer;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
if (option.trailing && lastArgs) {
func.apply(lastThis, lastArgs);
lastArgs = lastThis = null;
}
}, wait);
if (shouldCallNow) {
func.apply(lastThis, lastArgs);
lastArgs = lastThis = null;
}
};
}