← Alle AufgabenJavaScript · Middle

debounce

Schreib eine Funktion debounce(fn, ms). Sie liefert einen Wrapper, der fn erst ms Millisekunden nach dem letzten Aufruf des Wrappers aufruft. Jeder neue Aufruf startet den Countdown neu.

fn bekommt die Argumente des letzten Aufrufs und dasselbe this, mit dem der Wrapper aufgerufen wurde. So bremst man üblicherweise die Suche beim Tippen: die Anfrage geht raus, sobald der Nutzer aufhört zu tippen.

Tests (4)

  1. const f = fn();
    const d = debounce(f, 50);
    d(1); d(2); d(3);
    expect(f).toHaveBeenCalledTimes(0);
    await wait(80);
    expect(f).toHaveBeenCalledTimes(1);
    expect(f).toHaveBeenLastCalledWith(3);
  2. const f = fn();
    const d = debounce(f, 50);
    d('a');
    await wait(30);
    d('b');
    await wait(30);
    expect(f).toHaveBeenCalledTimes(0);
    await wait(45);
    expect(f).toHaveBeenCalledTimes(1);
    expect(f).toHaveBeenLastCalledWith('b');
  3. const f = fn();
    const d = debounce(f, 30);
    d(1);
    await wait(50);
    d(2);
    await wait(50);
    expect(f).toHaveBeenCalledTimes(2);
  4. let seen;
    const obj = { value: 42 };
    obj.read = debounce(function () { seen = this.value; }, 20);
    obj.read();
    await wait(40);
    expect(seen).toBe(42);