Skip to content

Instantly share code, notes, and snippets.

@micha
Last active October 30, 2016 02:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save micha/fa95fc3731c29abd71ff to your computer and use it in GitHub Desktop.
Save micha/fa95fc3731c29abd71ff to your computer and use it in GitHub Desktop.
Create a cell that only updates at most once every so many milliseconds
(defn throttle [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 (throttle 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