Reputation: 5968
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?
Upvotes: 3
Views: 4666
Reputation: 31024
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>
Upvotes: 2
Reputation: 24660
I believe you have a syntax error. Missing an arrow function on second setTimeout.
Try this please;
setTimeout(()=> {
this.setState((state, props) => ({ activateLightColorForRed: true }), () => {
setTimeout(()=> {
this.setState(()=> ({ activateLightColorForRed: false }))
}, 3000);
red.play();
})
}, 3000);
Upvotes: 0