UNPKG

1.38 kBJavaScriptView Raw
1/**
2 * 节流函数;当被调用 n 毫秒后才会执行,如果在这时间内又被调用则至少每隔 n 秒毫秒调用一次该函数
3 *
4 * @param {Function} callback 回调
5 * @param {Number} wait 多少秒毫
6 * @param {Object} options 参数{leading: 是否在之前执行, trailing: 是否在之后执行}
7 * @return {Function}
8 */
9function 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
50module.exports = throttle