Skip to content

Instantly share code, notes, and snippets.

@gtebbutt
Created December 19, 2014 14:17
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtebbutt/5e21f2e49592559f5043 to your computer and use it in GitHub Desktop.
Save gtebbutt/5e21f2e49592559f5043 to your computer and use it in GitHub Desktop.
Linear animation generator for Om & React
(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
))
@gtebbutt
Copy link
Author

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 to om/transact! or om/update-state! in order to animate the component property.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment