Last active
May 11, 2017 12:55
-
-
Save owenrh/8baeb98c5081ea648381 to your computer and use it in GitHub Desktop.
Clojurescript browser event handler debouncing (via core.async)
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
;; this is not a windowed debounce, it is a paused debounce | |
;; (the timer is reset on each non-timer value) | |
(defn debounce [ms somefunc] | |
(let [in (chan) | |
out (chan)] | |
; debounce in channel - based on https://gist.github.com/scttnlsn/9744501 | |
(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 (if new-val (recur new-val) (close! out))))) | |
; call debounced function on the given function/handler | |
(go-loop [] | |
(let [val (<! out)] | |
(somefunc val) | |
(recur))) | |
;return in event channel | |
in)) | |
(def in-channel (debounce 300 #(println %))) | |
(doseq [n (range 600)] (put! in-channel n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment