Last active
October 30, 2016 02:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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