Skip to content

Instantly share code, notes, and snippets.

@saurabhpati
Created November 13, 2017 04:11
Show Gist options
  • Save saurabhpati/927b4e8a69b17b722f464fef8a89035f to your computer and use it in GitHub Desktop.
Save saurabhpati/927b4e8a69b17b722f464fef8a89035f to your computer and use it in GitHub Desktop.
Start and Stop the Clock
import React from 'react';
export default Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
isClockRunning: true
}
}
render() {
return (
<div>
<h2>Hello World, Its { this.state.date.toLocaleString() } </h2>
<button onClock={ this.toggleState }>{ this.isClockRunning : 'STOP': 'START' }</button>
</div>
);
}
componentDidMount() {
this.setTimer();
}
componentWillUnmount() {
clearInterval(this.timerId);
}
setTimer() {
this.timerId = setInterval(() => this.tick(), 1000);
}
tick() {
this.setState({
date: new Date()
});
}
toggleState = () => {
this.setState(prevState => {
prevState.isClockRunning ? clearInterval(this.timerId) : this.setTimer();
return { isClockRunning: !prevState.isClockRunning };
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment