-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdebounce.js
40 lines (34 loc) · 883 Bytes
/
debounce.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
export function throttle(callback, wait, { start = true, middle = true, once = false }){
let last = 0
let timer
let cancelled = false
const fn = function (...args) {
if (cancelled) {
return
}
const delta = Date.now() - last
last = Date.now()
if (start) {
start = false
callback(...args)
once && fn.cancel()
} else if ((middle && delta < wait) || !middle) {
clearTimeout(timer)
timer = setTimeout(function () {
last = Date.now()
callback(...args)
once && fn.cancel()
},
!middle ? wait : wait - delta
)
}
}
fn.cancel = function () {
clearTimeout(timer)
cancelled = true
}
return fn
}
export function debounce(callback, wait, { start = false, middle = false, once = false }) {
return throttle(callback, wait, {start, middle, once})
}