Skip to content

Instantly share code, notes, and snippets.

@c-garcia
Last active August 29, 2015 14:17
Show Gist options
  • Save c-garcia/75080c93188ca5811fb5 to your computer and use it in GitHub Desktop.
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
;; 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