I am new to working with React and as an exercise have tried to modify the clock example from React's splash page. The goal is to have the seconds count at one interval and change circle's color at a more rapid interval.
I have tried to do this by using setTimeout functions for the changes to the circle
and called them from within the tick function, but the setTimeout calls are not being
recognized.
Is this an issue with React and the setInterval conflicting with the setTimeout?
If so what is the best way to achieve offset timed events?
Thank you for your time.
<!doctype html>
<html>
<head>
<title>Timer</title>
<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<link rel="stylesheet" href="styles.css" >
</head>
<body>
<div id="root"></div>
</body>
<script type="text/babel">
var changed = false;
class GameDisplay extends React.Component{
constructor(props){
super(props);
this.colorChange = this.colorChange.bind(this);
this.state = {
secondsElapsed: 0,
};
}
tick(){
setTimeout(() => this.colorChange(), 250);
setTimeout(() => this.colorChange(), 250);
this.colorChange();
this.setState((prevState) => ({
secondsElapsed: prevState.secondsElapsed + 1,
}));
}
colorChange(){
var tgt = document.getElementById("heart");
if (changed){
tgt.style.fill = "red";
} else {
tgt.style.fill = "green";
}
changed = !changed;
}
componentDidMount(){
this.interval = setInterval(() => this.tick(), 1000);
}
componentWillUnmount(){
clearInterval(this.interval);
}
render(){
return(
<div>
<h1>Seconds Elapsed: {this.state.secondsElapsed}</h1>
<svg id="main_disp" width="300" height="300">
<circle cx="150" cy="150" r="50" fill="black" />
<circle id="heart" cx="150" cy="150" r="30" fill="red" />
</svg>
</div>
);
}
}
class App extends React.Component {
render(){
return(
<div>
<GameDisplay />
</div>
)
};
}
ReactDOM.render(
<App />,
document.getElementById("root")
);
</script>
</html>