consider the following core-async code. It prints the string "tick" every 2 seconds:
(go-loop []
(<! (timeout 2000))
(prn "tick")
(recur))
I'm looking for a possibility to start and stop the interval from outside via functions.
The only thing that came to my mind was this:
(def running (atom false))
(defn start []
(reset! running true)
(go (loop []
(<! (timeout 2000))
(prn "tick")
(when @running (recur)))))
(defn stop []
(reset! running false))
Is this the way to go? Or would you do something else?
Here's what I would do:
Example:
This way, all your state is local and is handled via channels and go blocks, rather than using a global atom. Since the work done in each iteration of the loop is more or less constant, your actual interval time should be fairly close to the number of
msecs
you pass in.Or if you want to guarantee that the different calls to
f
are executed in chronological order, you could do something like this instead:(The usage of this function is the same as that of my earlier
interval
function.)Here all the calls to
f
are in the same loop. I'm using a dropping buffer, so if a call tof
takes longer thanmsecs
, future calls may start getting dropped to keep up.