1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | function throttle (callback, wait, options) {
|
10 | var args, context
|
11 | var opts = options || {}
|
12 | var runFlag = false
|
13 | var timeout = 0
|
14 | var optLeading = 'leading' in opts ? opts.leading : true
|
15 | var optTrailing = 'trailing' in opts ? opts.trailing : false
|
16 | var runFn = function () {
|
17 | runFlag = true
|
18 | callback.apply(context, args)
|
19 | timeout = setTimeout(endFn, wait)
|
20 | }
|
21 | var endFn = function () {
|
22 | timeout = 0
|
23 | if (!runFlag && optTrailing === true) {
|
24 | runFn()
|
25 | }
|
26 | }
|
27 | var cancelFn = function () {
|
28 | var rest = timeout !== 0
|
29 | clearTimeout(timeout)
|
30 | runFlag = false
|
31 | timeout = 0
|
32 | return rest
|
33 | }
|
34 | var throttled = function () {
|
35 | args = arguments
|
36 | context = this
|
37 | runFlag = false
|
38 | if (timeout === 0) {
|
39 | if (optLeading === true) {
|
40 | runFn()
|
41 | } else if (optTrailing === true) {
|
42 | timeout = setTimeout(endFn, wait)
|
43 | }
|
44 | }
|
45 | }
|
46 | throttled.cancel = cancelFn
|
47 | return throttled
|
48 | }
|
49 |
|
50 | module.exports = throttle
|