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

debounce

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

fn отримує аргументи останнього виклику й той самий this, з яким викликали обгортку. Так зазвичай обмежують пошук під час введення: запит іде, коли користувач перестав друкувати.

Тести (4)

  1. const f = fn();
    const d = debounce(f, 50);
    d(1); d(2); d(3);
    expect(f).toHaveBeenCalledTimes(0);
    await wait(80);
    expect(f).toHaveBeenCalledTimes(1);
    expect(f).toHaveBeenLastCalledWith(3);
  2. const f = fn();
    const d = debounce(f, 50);
    d('a');
    await wait(30);
    d('b');
    await wait(30);
    expect(f).toHaveBeenCalledTimes(0);
    await wait(45);
    expect(f).toHaveBeenCalledTimes(1);
    expect(f).toHaveBeenLastCalledWith('b');
  3. const f = fn();
    const d = debounce(f, 30);
    d(1);
    await wait(50);
    d(2);
    await wait(50);
    expect(f).toHaveBeenCalledTimes(2);
  4. let seen;
    const obj = { value: 42 };
    obj.read = debounce(function () { seen = this.value; }, 20);
    obj.read();
    await wait(40);
    expect(seen).toBe(42);