forked from bjoerge/debounce-promise
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (41 loc) · 929 Bytes
/
index.js
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
39
40
41
42
43
44
/* global setTimeout, clearTimeout */
export default function debounce(fn, wait = 0, {leading = false} = {}) {
let nextArgs
let pending
let resolve
let reject
let timer
return function (...args) {
nextArgs = args
if (!pending) {
if (leading) {
pending = fn(...nextArgs)
} else {
pending = new Promise((_resolve, _reject) => {
resolve = _resolve
reject = _reject
})
}
}
clearTimeout(timer)
timer = setTimeout(run.bind(null, nextArgs, resolve, reject), getWait(wait))
return pending
}
function run(_nextArgs, _resolve, _reject) {
fn(..._nextArgs).then(_resolve, _reject)
clear()
}
function clear() {
nextArgs = null
resolve = null
reject = null
pending = null
timer = null
}
function getWait(_wait) {
if (typeof _wait === 'function') {
return _wait()
}
return _wait
}
}