← All tasksJavaScript · Middle

throttle

Write a function throttle(fn, ms). The wrapper calls fn immediately on the first call, and after that at most once every ms milliseconds.

If the wrapper was called during the wait, fn runs once more at the end of the window with the arguments of the last of those calls. Calls in between are dropped. This is how scroll and resize handlers are limited.

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