← 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.
Strg+Enter führt die Tests aus. Tab rückt ein; um den Editor per Tastatur zu verlassen, drücke Esc und dann Tab. Der Code wird in diesem Browser gespeichert.
Tests (4)
const f = fn(); const t = throttle(f, 50); t(1); expect(f).toHaveBeenCalledTimes(1); expect(f).toHaveBeenLastCalledWith(1);
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);
const f = fn(); const t = throttle(f, 40); t(1); await wait(60); t(2); expect(f).toHaveBeenCalledTimes(2);
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);