frontend-challenges icon indicating copy to clipboard operation
frontend-challenges copied to clipboard

459 - Debounce with Leading & Trailing - javascript

Open jsartisan opened this issue 2 months ago • 0 comments

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;
}

jsartisan avatar Sep 22 '25 16:09 jsartisan