Add debounce to tasq

This commit is contained in:
Jerko Steiner 2019-08-26 20:00:48 +07:00
parent 359c6afd08
commit 803bbfa0fe
3 changed files with 31 additions and 1 deletions

View File

@ -0,0 +1,17 @@
import {debounce} from './debounce'
describe('debounce', () => {
it('executes only once', async () => {
const add = jest.fn()
const d = debounce(add, 0)
d(1, 2)
d(3, 4)
d(5, 6)
d(7, 8)
await new Promise(resolve => setTimeout(resolve, 0))
expect(add.mock.calls).toEqual([[ 7, 8 ]])
})
})

View File

@ -0,0 +1,13 @@
export function debounce<A, R>(fn: (...args: A[]) => R, delay: number) {
let timeout: NodeJS.Timeout | null = null
return async function debounceImpl(...args: A[]) {
if (timeout) {
clearTimeout(timeout)
}
timeout = setTimeout(() => {
fn(...args)
}, delay)
}
}

View File

@ -1 +1 @@
export * from './debounce'