Skip to content

Instantly share code, notes, and snippets.

@gt3
Created August 5, 2017 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gt3/7d1318f18c2b9c394fac503097702c89 to your computer and use it in GitHub Desktop.
Save gt3/7d1318f18c2b9c394fac503097702c89 to your computer and use it in GitHub Desktop.
throttle debounce with csp channels
/***** demo: debounce *****/
let dIn = chan(buffers.dropping(1)),
j = 1
let schedulePuts = () => setTimeout(() => putAsync(dIn, j++), j * 10)
let printAndInc = msg => {
if (msg >= 20) dIn.close()
console.log(msg)
}
throttle(printAndInc, 500, dIn)
setInterval(schedulePuts, 100)
/***** demo: throttle *****/
let print = msg => console.log(msg)
let tIn = chan(10),
tOut = chan(1)
for (var i = 1; i <= 10; i++) putAsync(tIn, i)
tIn.close()
setTimeout(() => {
console.log("-- tOut close --")
tOut.close()
}, 2500)
throttle(print, 500, tIn, tOut)
let { go, chan, poll, put, putAsync, timeout, NO_VALUE, CLOSED, buffers } = csp
function* readThenCall(cb, inch, delay = 0) {
let msg = yield inch,
cancelled
let cancel = () => {
cancelled = true
}
while (msg !== CLOSED) {
cb(msg, cancel)
if (cancelled) break
if (delay > 0) yield timeout(delay)
msg = yield inch
}
}
function* readThenPut(outch, inch, delay = 0) {
let msg = yield inch,
cancelled
while (msg !== CLOSED) {
cancelled = !(yield put(outch, msg))
if (cancelled) break
if (delay > 0) yield timeout(delay)
msg = yield inch
}
}
function* readThenPutThrottled(delay, inch, outch) {
let msg = poll(inch),
cancelled
if (msg !== NO_VALUE) cancelled = !(yield put(outch, msg))
if (!cancelled) go(readThenPut, [outch, inch, delay])
}
function throttle(cb, delay, inch, outch = chan(1)) {
go(readThenCall, [cb, outch])
go(readThenPutThrottled, [delay, inch, outch])
return outch
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment