3

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?

1
  • removing the callback on setstate. then below setTimeOut(the parent?), after 3 seconds it'll be evaluated. right? but setstate don't work. Commented Sep 9, 2017 at 11:25

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.