函数防抖和节流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function debounce(func, wait, immediate = true) {
let timer = 0

return function(...args) {
if (timer) {
clearTimeout(timer)
} else {
if (immediate) {
func.apply(func, args)
}
}

timer = setTimeout(() => {
timer = 0
if (!immediate) {
func.apply(func, args)
}
}, wait)
}
}
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
function getNow() {
return + new Date()
}


function throttle(func, wait) {
let [now, previous, timer, remainTime] = [0, 0, 0, 0]

const later = (...params) => setTimeout(() => {
func.apply(func, params)
previous = now
timer = 0
}, remainTime)

return function(...params) {
now = getNow()
// if if's the first time
if (!previous) {
previous = now
}

remainTime = wait - (now - previous)
// if there is not a timer, then create it
if (!timer) {
timer = later(...params)
}
}
}
分享到: