mutant
Version:
Create observables and map them to DOM elements. Massively inspired by hyperscript and observ-*. No virtual dom, just direct observable bindings. Unnecessary garbage collection is avoided by using mutable objects instead of blasting immutable junk all ove
56 lines (48 loc) • 1.3 kB
JavaScript
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 () {}