Skip to content

Instantly share code, notes, and snippets.

@xfsnowind
Created October 23, 2015 22:08

Revisions

  1. xfsnowind created this gist Oct 23, 2015.
    27 changes: 27 additions & 0 deletions debounce.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    (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))