frontend-challenges
frontend-challenges copied to clipboard
459 - Debounce with Leading & Trailing - javascript
index.js
export function debounce(func, delay, options = {}) {
const { leading = false, trailing = true } = options;
let timerId;
const debounced = function () {
const context = this;
const args = arguments;
if (leading && !timerId) func.apply(context, args);
clearTimeout(timerId);
timerId = setTimeout(function () {
if (trailing) func.apply(context, args);
}, delay);
};
debounced.cancel = () => {
clearTimeout(timerId);
};
return debounced;
}