Files: 89e85f9009db15cde0d4a19d0f6fd5167a25d808 / watch-throttle.js
1063 bytesRaw
1 | var resolve = require('./resolve') |
2 | var isObservable = require('./is-observable') |
3 | |
4 | module.exports = function throttledWatch (obs, minDelay, listener, opts) { |
5 | var throttling = false |
6 | var lastRefreshAt = 0 |
7 | var lastValueAt = 0 |
8 | var throttleTimer = null |
9 | |
10 | var broadcastInitial = !opts || opts.broadcastInitial !== false |
11 | |
12 | // default delay is 20 ms |
13 | minDelay = minDelay || 20 |
14 | |
15 | // run unless opts.broadcastInitial === false |
16 | if (broadcastInitial) { |
17 | listener(resolve(obs)) |
18 | } |
19 | |
20 | if (isObservable(obs)) { |
21 | return obs(function (v) { |
22 | if (!throttling) { |
23 | if (Date.now() - lastRefreshAt > minDelay) { |
24 | refresh() |
25 | } else { |
26 | throttling = true |
27 | throttleTimer = setInterval(refresh, minDelay) |
28 | } |
29 | } |
30 | lastValueAt = Date.now() |
31 | }) |
32 | } else { |
33 | return noop |
34 | } |
35 | |
36 | function refresh () { |
37 | lastRefreshAt = Date.now() |
38 | listener(obs()) |
39 | if (throttling && lastRefreshAt - lastValueAt > minDelay) { |
40 | throttling = false |
41 | clearInterval(throttleTimer) |
42 | } |
43 | } |
44 | } |
45 | |
46 | function noop () {} |
47 |
Built with git-ssb-web