Skip to content

Instantly share code, notes, and snippets.

@dually8
Created April 11, 2023 17:12
Show Gist options
  • Save dually8/5bd71fbbbec5c12799c39b789e58c3d5 to your computer and use it in GitHub Desktop.
Save dually8/5bd71fbbbec5c12799c39b789e58c3d5 to your computer and use it in GitHub Desktop.
Debounce Function in Typescript
import { debounce } from './debounce';
describe('Debounce', () => {
it('should test debounce', () => {
jest.useFakeTimers();
const oneSecond = 1000;
const obj = {
foo: 'foo',
bar: 'bar',
}
const setFooDebounced = debounce((newFoo) => {
obj.foo = newFoo;
}, oneSecond);
setFooDebounced('foo2')
expect(obj.foo).toEqual('foo');
setFooDebounced('foo3')
jest.advanceTimersByTime(oneSecond);
expect(obj.foo).toEqual('foo3');
})
})
export function debounce<T extends (...args: any[]) => any>(func: T, delay: number) {
let timeoutId: ReturnType<typeof setTimeout>;
return function (this: unknown, ...args: Parameters<T>) {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
func.apply(this, args);
timeoutId = null;
}, delay);
} as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment