-
Notifications
You must be signed in to change notification settings - Fork 26
/
自测防抖和节流.js
40 lines (38 loc) · 833 Bytes
/
自测防抖和节流.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
function debounce (fn, delay, immediate) {
let timer
return function (...args) {
let _this = this
if (immediate) {
fn.call(_this, ...args)
immediate = false
}
timer && clearTimeout(timer)
timer = setTimeout(function () {
fn.call(_this, ...args)
}, delay)
}
}
// function throttle (fn, delay, immediate) {
// let timer
// return function (...args) {
// let _this = this
// if (immediate) {
// fn.call(_this, ...args)
// immediate = false
// }
// if (timer) return
// timer = setTimeout(function () {
// fn.call(_this, ...args)
// timer = null
// }, delay)
// }
// }
function throttle (fn, delay) {
let now = 0
return function (...args) {
if (Date.now() - now > delay) {
fn(...args)
now = Date.now()
}
}
}