-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththrottle.js
45 lines (35 loc) · 899 Bytes
/
throttle.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
45
export function throttle(
func,
wait = 1000, //ms
options = {
leading: false,
trailing: false,
},
) {
let context, args = [], result
let timeout = null
let previous = 0
const later = function () {
previous = options.leading ? Date.now() : 0
timeout = null
result = func.apply( context, args || [])
context = args = null
}
return function () {
const now = Date.now()
if ( !previous && options.leading === false ) previous = now
const remaining = wait - ( now - previous )
context = this
args = arguments
if ( remaining <= 0 ) {
if ( timeout ) clearTimeout( timeout )
timeout = null
previous = now
result = func.apply( context, args )
context = args = null
} else if ( !timeout && options.trailing !== false ) {
timeout = setTimeout( later, remaining )
}
return result
}
}