Skip to content

Instantly share code, notes, and snippets.

@eneroth
Last active February 19, 2021 11:14
Show Gist options
  • Save eneroth/66449c7ea1514a08d302 to your computer and use it in GitHub Desktop.
Save eneroth/66449c7ea1514a08d302 to your computer and use it in GitHub Desktop.
Incrementing timer in React, in JavaScript and ClojureScript (Reagent)
var Timer = React.createClass({
getInitialState: function() {
return {secondsElapsed: 0};
},
tick: function() {
this.setState({secondsElapsed: this.state.secondsElapsed + 1});
},
componentDidMount: function() {
this.interval = setInterval(this.tick, 1000);
},
componentWillUnmount: function() {
clearInterval(this.interval);
},
render: function() {
return (
<div>Seconds Elapsed: {this.state.secondsElapsed}</div>
);
}
});
React.render(<Timer />, mountNode);
;; State
(def app-state (atom 0)) ;; Initial value is 0
;; Increment seconds
(js/setInterval #(swap! app-state inc) 1000) ;; Increment app-state every 1000ms
;; "Seconds elapsed" component
(defn timer []
[:div (str "Seconds elapsed: " @app-state)])
(render-component [timer] (get-element :body)) ;; Render it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment