Skip to content

Instantly share code, notes, and snippets.

@Deraen
Forked from scttnlsn/debounce.cljs
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Deraen/946ac9e6c6211c83f1e9 to your computer and use it in GitHub Desktop.
Save Deraen/946ac9e6c6211c83f1e9 to your computer and use it in GitHub Desktop.
(defn debounce
"Creates a channel which will change put a new value to the output channel
after timeout has passed. Each value change resets the timeout. If value
changes more frequently only the latest value is put out.
When input channel closes, the output channel is closed."
[in ms]
(let [out (chan)]
(go-loop [last-val nil]
(let [val (if (nil? last-val) (<! in) last-val)
timer (timeout ms)]
(alt!
in ([v] (if v
(recur v)
(close! out)))
timer ([_] (do (>! out val) (recur nil))))))
out))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment