Created
April 11, 2023 17:12
-
-
Save dually8/5bd71fbbbec5c12799c39b789e58c3d5 to your computer and use it in GitHub Desktop.
Debounce Function in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}) | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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