Skip to content

Instantly share code, notes, and snippets.

@ul
Forked from micha/throttle.cljs.hl
Last active August 29, 2015 14:27
Show Gist options
  • Save ul/d99a517cd528cd69f49a to your computer and use it in GitHub Desktop.
Save ul/d99a517cd528cd69f49a to your computer and use it in GitHub Desktop.
Create a cell that only updates at most once every so many milliseconds
(defn debounce [c ms]
(let [queued? (atom false)]
(with-let [ret (cell @c)]
(add-watch c (gensym)
#(when-not @queued?
(reset! queued? true)
(with-timeout ms
(reset! queued? false)
(reset! ret @c)))))))
(def test1 (cell 0))
(def test2 (debounce test1 1000))
(with-interval 100 (swap! test1 inc))
(cell= (pr :test2 test2))
;; js console output:
;;
;; :test2 0
;; :test2 10
;; :test2 20
;; :test2 30
;; ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment