Start · Sprachen · JavaScript · Snippets · Debounce und Throttle

Debounce und Throttle

Sonstiges

Debounce führt eine Funktion erst aus, wenn die Aufrufe eine Weile pausieren (z. B. Suche, Resize). Throttle führt sie höchstens einmal pro Intervall aus (z. B. Scroll), der letzte Aufruf geht nicht verloren.

Code

// Debounce: erst ausführen, wenn seit dem letzten Aufruf `wait` ms vergangen sind
const debounce = (fn, wait = 200) => {
  let t;
  const d = function (...args) {
    clearTimeout(t);
    t = setTimeout(() => fn.apply(this, args), wait);
  };
  d.cancel = () => clearTimeout(t); // z. B. beim Unmount aufrufen
  return d;
};

// Throttle: höchstens 1× pro `wait` ms, der letzte Aufruf wird nachgeholt
const throttle = (fn, wait = 200) => {
  let last = 0, t;
  const th = function (...args) {
    const run = () => { last = Date.now(); fn.apply(this, args); };
    clearTimeout(t);
    const rest = wait - (Date.now() - last);
    rest <= 0 ? run() : (t = setTimeout(run, rest));
  };
  th.cancel = () => clearTimeout(t);
  return th;
};

// Verwendung
input.addEventListener('input', debounce(e => search(e.target.value), 300));
window.addEventListener('scroll', throttle(() => updateHeader(scrollY), 100));