Last active
August 29, 2015 14:17
-
-
Save c-garcia/75080c93188ca5811fb5 to your computer and use it in GitHub Desktop.
Repeatedly execute a function with side effects with certain period while a reference evaluates to true
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
;; Based on | |
;; http://bjeanes.com/2012/09/call-clojure-function-on-a-timer | |
;; Example: | |
;; (def flag (atom true)) | |
;; (tick-while flag 1000 (fn [s] (println (str s ":" (System/currentTimeMillis)))) "Time") | |
;; wait for some time and | |
;; (swap! flag (fn [_] false)) | |
(defn tick-while | |
"Executes the function f (side-effects) with args every t ms until p-ref de-references to false." | |
[p-ref t f & args] | |
(letfn [(the-f [] #(apply f args)) | |
(call-seq [] (lazy-seq (when @p-ref (cons (the-f) (call-seq) ))))] | |
(doseq [ff (call-seq)] | |
(ff) | |
(Thread/sleep t)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment