← Усі задачіJavaScript · Middle

throttle

Напишіть функцію throttle(fn, ms). Обгортка викликає fn одразу під час першого виклику, а потім не частіше ніж раз на ms мілісекунд.

Якщо під час очікування обгортку викликали, наприкінці вікна fn викликається ще раз - з аргументами останнього з цих викликів. Проміжні виклики губляться. Так обмежують обробники scroll і resize.

Тести (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);