Skip to content

Instantly share code, notes, and snippets.

@prdxs
Created April 20, 2021 18:50
Show Gist options
  • Save prdxs/1b8b1b29970a2178350e3b3b90bc6f12 to your computer and use it in GitHub Desktop.
Save prdxs/1b8b1b29970a2178350e3b3b90bc6f12 to your computer and use it in GitHub Desktop.
class StoppableClock extends Component {
constructor(props) {
super(props);
this.state = {
time: new Date().toLocaleTimeString(),
isRunning: true,
};
}
componentDidMount() {
this.intervalId = setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
componentDidUpdate(prevProps, prevState) {
// Stopping clock
if (prevState.isRunning && !this.state.isRunning) {
clearInterval(this.intervalId);
}
// Re-starting clock
if (!prevState.isRunning && this.state.isRunning) {
this.intervalId = setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() });
}, 1000);
}
}
toggle = () => {
this.setState(({ isRunning }) => ({ isRunning: !isRunning }));
}
render() {
const { className, style } = this.props;
const { time } = this.state;
return (
<div className={clsx('StoppableClock', className)} style={style}>
<span className="StoppableClock-time">{time}</span>
<button className="StoppableClock-button" onClick={this.toggle}>Toggle</button>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment