← Wszystkie zadaniaJavaScript · Middle

throttle

Napisz funkcję throttle(fn, ms). Opakowanie wywołuje fn od razu przy pierwszym wywołaniu, a potem nie częściej niż raz na ms milisekund.

Jeśli w czasie oczekiwania opakowanie było wywoływane, na końcu okna fn uruchamia się jeszcze raz z argumentami ostatniego z tych wywołań. Wywołania pośrednie przepadają. Tak ogranicza się handlery scroll i resize.

Testy (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);