Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

throttle and debounce #138

Open
gt3 opened this issue Aug 5, 2017 · 2 comments
Open

throttle and debounce #138

gt3 opened this issue Aug 5, 2017 · 2 comments

Comments

@gt3
Copy link

gt3 commented Aug 5, 2017

Controlling streaming data with channels is a powerful concept. Yet too much boilerplate goes into implementing functions like throttle and debounce.

I'm proposing that we add few helpers to provide out of the box standard functionality.

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])
}

// export
function throttle(cb, delay, inch, outch = chan(1)) {
  go(readThenCall, [cb, outch])
  go(readThenPutThrottled, [delay, inch, outch])
  return outch
}

I can create a PR once we agree on the requirements.

cc: @hung-phan @ubolonton
related to #133

@frankandrobot
Copy link
Contributor

So note that my example already has a working debounce. The only thing missing is that it needs to stop when the input channel is closed.

@gt3
Copy link
Author

gt3 commented Aug 9, 2017

Totally your code inspired me to open this issue. I just refactored it a bit. I wanted to show how simple it is to go from throttle to debounce using Channels as the interface. Thanks again for making that example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants