1 | var now = Date.now || function now () { return new Date().getTime() }
|
2 |
|
3 | module.exports = debounce
|
4 |
|
5 | function debounce (func, wait, immediate) {
|
6 | var timer, context, timestamp, result
|
7 | var args = []
|
8 | if (wait == null) wait = 100
|
9 |
|
10 | function onTimeout () {
|
11 | var elapsed = now() - timestamp
|
12 |
|
13 | if (elapsed < wait && elapsed > 0) {
|
14 | timer = setTimeout(onTimeout, wait - elapsed)
|
15 | } else {
|
16 | timer = null
|
17 | if (!immediate) {
|
18 | result = call()
|
19 | if (!timer) reset()
|
20 | }
|
21 | }
|
22 | }
|
23 |
|
24 | function call () {
|
25 | return func.call(context, args)
|
26 | }
|
27 |
|
28 | function reset () {
|
29 | context = null
|
30 | args = []
|
31 | }
|
32 |
|
33 | return function debounced () {
|
34 | context = this
|
35 | args.push([].slice.call(arguments))
|
36 | timestamp = now()
|
37 | var callNow = immediate && !timer
|
38 | if (!timer) timer = setTimeout(onTimeout, wait)
|
39 | if (callNow) {
|
40 | result = call()
|
41 | reset()
|
42 | }
|
43 |
|
44 | return result
|
45 | }
|
46 | }
|