-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebounce.mjs
38 lines (25 loc) · 840 Bytes
/
debounce.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import { promises } from './promises.mjs'
export function debounce (callback, milliseconds = 0) {
const { resolve, reject, promise } = promises()
let timeout
innerDebounce.calls = []
async function innerDebounce (...args) {
innerDebounce.calls.push(args)
timeout && clearTimeout(timeout)
timeout = setTimeout(() => {
resolve(callback(innerDebounce.calls))
innerDebounce.calls = []
}, milliseconds)
return promise()
}
innerDebounce.reject = reject
// TODO: Consider adding a resolve for an early resolve.
return innerDebounce
}
export function debounceWithIndex (callback, milliseconds = 0) {
const innerDebounce = debounce(callback, milliseconds)
return async (...args) => {
const index = innerDebounce.calls.length
return (await innerDebounce(...args))[index]
}
}