Skip to content

Instantly share code, notes, and snippets.

@codecademydev

codecademydev/Clock.js Secret

Created Mar 9, 2021
Embed
What would you like to do?
Codecademy export
import React from 'react';
export class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
return (
<div>
{this.props.isPrecise
? this.state.date.toISOString()
: this.state.date.toLocaleTimeString()}
</div>
);
}
componentDidMount() {
const oneSecond = 1000;
this.intervalID = setInterval(() => {
this.setState({ date: new Date() });
}, oneSecond);
}
componentDidUpdate(prevProps) {
if(this.props.isPrecise === prevProps.isPrecise){
return;
}
clearInterval(this.intervalID);
let delay;
if(this.props.isPrecise){
delay = 100;
}else{
delay = 1000;
}
this.intervalID = setInterval(()=>{
this.setState({date: newDate()})
},delay)
}
componentWillUnmount() {
clearInterval(this.intervalID);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment