Last active
August 29, 2015 14:27
-
-
Save owenrh/1a059348df7ed00c1aec to your computer and use it in GitHub Desktop.
Clojurescript browser event handler debouncing (via core.async) - window-based approach.
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
;; window-based debounce | |
;; (passes the existing timer through on recur) | |
(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 | |
timer (timeout ms)] | |
(let [val (if (nil? last-val) (<! in) last-val) | |
[new-val ch] (alts! [in timer])] | |
(condp = ch | |
timer (do (>! out val) (recur nil (timeout ms))) | |
in (if new-val (recur new-val timer) (close! out))))) | |
; call debounced function on the given function/handler | |
(go-loop [] | |
(let [val (<! out)] | |
(somefunc val) | |
(recur))) | |
;return in event channel | |
in)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment