Skip to content

Instantly share code, notes, and snippets.

@xfsnowind
Created October 23, 2015 22:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xfsnowind/e15cc2e6da74df81f129 to your computer and use it in GitHub Desktop.
Save xfsnowind/e15cc2e6da74df81f129 to your computer and use it in GitHub Desktop.
The clojure version with library core.async of debounce function
(defn debounce-chan
"Taken from https://github.com/swannodette/async-tests
A little different with original one, write to channel after the interval
instead of doing it in the beginning"
([source msecs]
(debounce-chan (chan) source msecs))
([c source msecs]
(go-loop [state ::init
last-one nil
cs [source]]
(let [[_ threshold] cs
[v sc] (alts! cs)]
(condp = sc
source (condp = state
::init (recur ::debouncing
v
(conj cs (timeout msecs)))
::debouncing (recur state
v
(conj (pop cs) (timeout msecs))))
threshold (if last-one
(do (>! c last-one)
(recur ::init
nil
(pop cs)))
(recur ::init last-one (pop cs))))))
c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment