Syntax previewClick to edit
12345
export default function debounce(fn, delay) {
// TODO: Return a debounced function that delays execution until delay ms have passed
throw new Error('Not implemented');
}
Syntax previewClick to edit
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
import debounce from './debounce';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
describe('debounce', () => {
test('does not call synchronously and runs after delay', async () => {
const calls = [];
const debounced = debounce((value) => { calls.push(value); }, 80);
debounced('A');
expect(calls).toEqual([]);
await sleep(90);
expect(calls).toEqual(['A']);
});
test('rapid calls only run the latest argument after the final delay', async () => {
const calls = [];
const debounced = debounce((value) => { calls.push(value); }, 100);
debounced('A'); // t=0
await sleep(50);
debounced('B'); // t=50
await sleep(40);
debounced('C'); // t=90
await sleep(95);
expect(calls).toEqual([]);
await sleep(20);
expect(calls).toEqual(['C']);
});
test('preserves this context and arguments', async () => {
const calls = [];
const debounced = debounce(function (value) {
calls.push(`${this.tag}:${value}`);
}, 60);
debounced.call({ tag: 'search-box' }, 'react');
await sleep(80);
expect(calls).toEqual(['search-box:react']);
});
});
Run tests to see results.