Skip to content

Instantly share code, notes, and snippets.

@owenrh
Last active August 29, 2015 14:27
Show Gist options
  • Save owenrh/1a059348df7ed00c1aec to your computer and use it in GitHub Desktop.
Save owenrh/1a059348df7ed00c1aec to your computer and use it in GitHub Desktop.
Clojurescript browser event handler debouncing (via core.async) - window-based approach.
;; 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