Created
March 24, 2014 17:03
-
-
Save scttnlsn/9744501 to your computer and use it in GitHub Desktop.
core.async debounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn debounce [in ms] | |
(let [out (chan)] | |
(go-loop [last-val nil] | |
(let [val (if (nil? last-val) (<! in) last-val) | |
timer (timeout ms) | |
[new-val ch] (alts! [in timer])] | |
(condp = ch | |
timer (do (>! out val) (recur nil)) | |
in (recur new-val)))) | |
out)) |
closing the in
when out
gets closed:
(defn debounce [in ms]
(let [out (chan)]
(go-loop [last-val nil]
(let [val (if (nil? last-val) (<! in) last-val)
timer (timeout ms)
[new-val ch] (alts! [in timer])]
(condp = ch
timer (do (when-not
(>! out val)
(close! in))
(recur nil))
in (if new-val (recur new-val)))))
out))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nice, just one comment, this implementation has one issue, that is when you close the
in
channel it gets into an infinite loop by recurring withnew-val
asnil
all the time, the fix is simple, just check the value when receiving fromin
: