Created
December 19, 2014 14:17
-
-
Save gtebbutt/5e21f2e49592559f5043 to your computer and use it in GitHub Desktop.
Linear animation generator for Om & React
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 animate-value | |
[start-val end-val duration] | |
(let [decrement? (< end-val start-val) | |
transmit-chan (chan) | |
cancel-chan (chan) | |
animation-interval 40 ;40 ms interval - 25fps | |
steps (/ duration animation-interval) | |
full-range (- start-val end-val) | |
per-step (util/abs (/ full-range steps)) | |
state (atom start-val) | |
animator (js/setInterval | |
(fn [] | |
(let [update-fn (if decrement? | |
#(- % per-step) | |
#(+ % per-step))] | |
(swap! state update-fn)) | |
(put! transmit-chan @state) | |
(put! cancel-chan @state)) | |
animation-interval) | |
] | |
(go | |
(loop [] | |
(let [value (<! cancel-chan)] | |
(when value | |
(when ((if decrement? <= >=) value end-val) | |
(js/clearInterval animator) | |
(put! transmit-chan end-val) ;In case we overshoot | |
(close! transmit-chan) | |
(close! cancel-chan)) | |
(recur))))) | |
transmit-chan | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick function to generate a linearly increasing/decreasing value across a range - timing is handled internally, so you can just read the output value in a
go
loop and feed that value straight toom/transact!
orom/update-state!
in order to animate the component property.