← All tasksJavaScript · Middle
debounce
Write a function debounce(fn, ms). It returns a wrapper that calls fn only ms milliseconds after the last call to the wrapper. Every new call restarts the countdown.
fn receives the arguments of the last call and the same this the wrapper was called with. This is the usual way to throttle search-as-you-type: the request goes out once the user stops typing.
Ctrl+Enter runs the tests. Tab indents; to leave the editor with the keyboard, press Esc and then Tab. Your code is saved in this browser.
Tests (4)
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);
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');
const f = fn(); const d = debounce(f, 30); d(1); await wait(50); d(2); await wait(50); expect(f).toHaveBeenCalledTimes(2);
let seen; const obj = { value: 42 }; obj.read = debounce(function () { seen = this.value; }, 20); obj.read(); await wait(40); expect(seen).toBe(42);