-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathwatch-throttle.js
55 lines (48 loc) · 1.27 KB
/
watch-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
46
47
48
49
50
51
52
53
54
55
var resolve = require('./resolve')
var isObservable = require('./is-observable')
module.exports = function throttledWatch (obs, minDelay, listener, opts) {
var throttling = false
var lastRefreshAt = 0
var lastValueAt = 0
var throttleTimer = null
var broadcasting = false
var broadcastInitial = !opts || opts.broadcastInitial !== false
// default delay is 20 ms
minDelay = minDelay || 20
// run unless opts.broadcastInitial === false
if (broadcastInitial) {
listener(resolve(obs))
}
if (isObservable(obs)) {
return obs(function (v) {
if (!throttling) {
if (Date.now() - lastRefreshAt > minDelay) {
if (opts && opts.nextTick) {
if (!broadcasting) {
broadcasting = true
setImmediate(refresh)
}
} else {
refresh()
}
} else {
throttling = true
throttleTimer = setInterval(refresh, minDelay)
}
}
lastValueAt = Date.now()
})
} else {
return noop
}
function refresh () {
broadcasting = false
lastRefreshAt = Date.now()
listener(obs())
if (throttling && lastRefreshAt - lastValueAt > minDelay) {
throttling = false
clearInterval(throttleTimer)
}
}
}
function noop () {}