code:
setTimeout(() => {
this.setState((state, props) => ({
activateLightColorForRed: true
}), () => {
setTimeout(
this.setState((state, props) => ({
activateLightColorForRed: false
})), 3000);
});
red.play()
}, 3000);
when there's no callback on react setstate it's working but I need to set activateLightColorForYellow to false after 3 seconds. if i use setstate outside setTimeout, setstate is not working. help?
The setState's callback is there for you to be sure the state has really been changed.
This is a small example of chained setTimout:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
title: "click me"
};
this.onClick = this.onClick.bind(this);
}
onClick(e) {
this.setState({ title: "value 1" }, () => {
setTimeout(() => {
this.setState({ title: "value 2" }, ()=>{
setTimeout(()=>{
this.setState({title: 'value 3'})
},1500);
});
}, 1000);
});
}
render() {
return (
<div>
<div onClick={this.onClick}>{this.state.title}</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With