← Alle AufgabenJavaScript · Middle

throttle

Schreib eine Funktion throttle(fn, ms). Der Wrapper ruft fn beim ersten Aufruf sofort auf und danach höchstens einmal alle ms Millisekunden.

Wurde der Wrapper während der Wartezeit aufgerufen, läuft fn am Ende des Fensters noch einmal mit den Argumenten des letzten dieser Aufrufe. Aufrufe dazwischen werden verworfen. So begrenzt man Handler für scroll und resize.

Tests (4)

  1. const f = fn();
    const t = throttle(f, 50);
    t(1);
    expect(f).toHaveBeenCalledTimes(1);
    expect(f).toHaveBeenLastCalledWith(1);
  2. const f = fn();
    const t = throttle(f, 50);
    t(1); t(2); t(3);
    expect(f).toHaveBeenCalledTimes(1);
    await wait(70);
    expect(f).toHaveBeenCalledTimes(2);
    expect(f).toHaveBeenLastCalledWith(3);
  3. const f = fn();
    const t = throttle(f, 40);
    t(1);
    await wait(60);
    t(2);
    expect(f).toHaveBeenCalledTimes(2);
  4. const f = fn();
    const t = throttle(f, 40);
    t(1); t(2);
    await wait(50);
    t(3);
    expect(f).toHaveBeenCalledTimes(2);
    await wait(50);
    expect(f).toHaveBeenCalledTimes(3);
    expect(f).toHaveBeenLastCalledWith(3);