Debounce without pulling in a library

Javascript

Twelve lines covering the case most projects add a dependency for, including cancelling a call that has not fired yet.

function debounce(fn, wait = 250) {
  let timer;
  const run = (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...args), wait);
  };
  run.cancel = () => clearTimeout(timer);
  return run;
}

More in JavaScript

Random picks