3

can someone tell me how to make this work in the loop fuction? how can I bind the loop function to constructor?

class Cookcoo extends React.Component{
    constructor(props){
        super(props);
        this.state={
            test:false
        }
        this.onPlay=this.onPlay.bind(this)
    }
    onPlay(){
            (function loop() {
            let randomTime = Math.round(Math.random() * 3000) + 500;
            setTimeout(()=> {
                this.setState({test:true}); 
                setTimeout(()=>this.setState({test:false}),500)
                loop();
            }, randomTime);

        }());
    }
3
  • 1
    one simple solution is let that = this; and use that inside loop function. Commented Jan 11, 2018 at 16:22
  • perfect, thank you very much Commented Jan 11, 2018 at 16:24
  • You could also declare loop with a fat arrow function. Commented Jan 11, 2018 at 16:30

2 Answers 2

2

One simple solution is use a extra variable to store the reference of this (class context) and use that variable inside loop function.

Like this:

onPlay(){

    let that = this;

    (function loop() {
        let randomTime = Math.round(Math.random() * 3000) + 500;
        setTimeout(()=> {
            that.setState({test:true}); 
            setTimeout(()=>that.setState({test:false}),500)
            loop();
        }, randomTime);
    }());
}
Sign up to request clarification or add additional context in comments.

Comments

1

You could bind the self executing function and then call the inner function with .call() like

onPlay() {
    (function loop() {
      let randomTime = Math.round(Math.random() * 3000) + 500;
      setTimeout(() => {
        console.log(this);
        this.setState({ test: true });
        setTimeout(() => this.setState({ test: false }, console.log(this.state.test)), 500)
        loop.call(this);
      }, randomTime);

    }.bind(this)());
  }

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.