forked from glidejs/glide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait.js
53 lines (48 loc) · 1.29 KB
/
wait.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
46
47
48
49
50
51
52
53
import { now } from './time'
/**
* Returns a function, that, when invoked, will only be triggered
* at most once during a given window of time.
*
* @param {Function} func
* @param {Number} wait
* @param {Object=} options
* @return {Function}
*
* @see https://github.com/jashkenas/underscore
*/
export function throttle (func, wait, options) {
let timeout, context, args, result
let previous = 0
if (!options) options = {}
let later = function () {
previous = options.leading === false ? 0 : now()
timeout = null
result = func.apply(context, args)
if (!timeout) context = args = null
}
let throttled = function () {
let at = now()
if (!previous && options.leading === false) previous = at
let remaining = wait - (at - previous)
context = this
args = arguments
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
previous = at
result = func.apply(context, args)
if (!timeout) context = args = null
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining)
}
return result
}
throttled.cancel = function () {
clearTimeout(timeout)
previous = 0
timeout = context = args = null
}
return throttled
}