1

I'm trying to change the states in a loop using setTimeout method. I have declared a default state in my constructor like this

constructor(){
        super();

        this.state = {

            postType:'star_rating'

        }

    }

I want to change the state in 5 seconds which i was able to achieve like this

setTimeout(() => {
            this.setState({
                postType: 'image_poll'
            });
        }, 5000);

The problem is after another 5 seconds it should change it to another state. And after another 5 seconds the state change should be repeated from the beginning. So in conclusion the state should change like this

A -> B -> C -> A -> B -> C -> A -> B -> C ....... continuously this should happen. How can i do this?

4
  • 2
    Use an array and a counter? Reset counter when > 2? Commented Oct 31, 2017 at 10:52
  • 1
    If you need to repeatedly perform an action then consider setInterval developer.mozilla.org/en-US/docs/Web/API/…. You can read the current state to decide what to transition to on each interval. Commented Oct 31, 2017 at 10:54
  • @mplungjan could you please show me how? Commented Oct 31, 2017 at 10:55
  • 1
    const states = ['image_poll','star_rating','whatever']; this.currentState = 0; setInterval(() => { this.setState({ if (this.currentState>2) { this.currentState=0; } this.setState({ postType: states[currentState] }) },5000); Commented Oct 31, 2017 at 11:01

1 Answer 1

1

That's just a simple state machine. This is one possible implementation:

setTimeout(() => {
    this.setState(getNextState());
}, 5000);

and

getNextState() {
  if (this.state.postType === 'star_rating') 
    return { postType: 'image_poll' };
  if (this.state.postType === 'image_poll')
    return { postType: 'third_state' };
  return { postType: 'star_rating' };
}
Sign up to request clarification or add additional context in comments.

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.