1

I am new to working with React and as an exercise have tried to modify the clock example from React's splash page. The goal is to have the seconds count at one interval and change circle's color at a more rapid interval.

I have tried to do this by using setTimeout functions for the changes to the circle and called them from within the tick function, but the setTimeout calls are not being recognized.

Is this an issue with React and the setInterval conflicting with the setTimeout? If so what is the best way to achieve offset timed events?

Thank you for your time.

<!doctype html>
<html>
<head>
<title>Timer</title>

<script src="https://unpkg.com/react@15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.34/browser.min.js"></script>
<link rel="stylesheet" href="styles.css" >
</head>

<body>
<div id="root"></div>
</body>
<script type="text/babel">

var changed = false;

class GameDisplay extends React.Component{
  constructor(props){
    super(props);
    this.colorChange = this.colorChange.bind(this);
    this.state = {
      secondsElapsed: 0,
    };
  }

  tick(){
    setTimeout(() => this.colorChange(), 250);
    setTimeout(() => this.colorChange(), 250);
    this.colorChange();
    this.setState((prevState) => ({
      secondsElapsed: prevState.secondsElapsed + 1,
    }));
  }

  colorChange(){
    var tgt = document.getElementById("heart");
    if (changed){
      tgt.style.fill = "red";
    } else {
      tgt.style.fill = "green";
    }
    changed =  !changed;
  }

  componentDidMount(){
    this.interval = setInterval(() => this.tick(), 1000);
  }

  componentWillUnmount(){
    clearInterval(this.interval);
  }

  render(){
    return(
    <div>
      <h1>Seconds Elapsed: {this.state.secondsElapsed}</h1>
      <svg id="main_disp" width="300" height="300">
        <circle cx="150" cy="150" r="50" fill="black" />
        <circle id="heart" cx="150" cy="150" r="30" fill="red" />
      </svg>
    </div>
  );
  }
}

class App extends React.Component {
  render(){
    return(
      <div>
      <GameDisplay />
      </div>
    )
  };
}



ReactDOM.render(
  <App />,
  document.getElementById("root")
);
</script>
</html>

1 Answer 1

3

TL;DR the reason you see no change is that you have two colorChange executions at the "same time", one overriding the other.

setTimeout(() => this.colorChange(), 250);
setTimeout(() => this.colorChange(), 250);

setTimeout is async and immediately returns so you schedule two colorChange executions after the "same" amount of time. Try to put the second call to timeout after 500ms and it works.

I used quotes on "same time" because setTimeout is not that accurate (by design) and JS is single threaded so those two executions happen somewhere close to the next 250ms and sequentially. But in any case they happen too fast for the eye to follow, also most modern browsers do batch rendering as an optimization step so the change may not happen at all.

===

But because you mentioned you're not familiar with react and this is a hands on exercise I'd say that you can do some changes to write this better (in react terms). See the example below:

<!doctype html>
<html>
  <head>
    <title>Timer</title>
    <script src="https://unpkg.com/react@15/dist/react.js"></script>
    <script src="https://unpkg.com/react-dom@15/dist/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.38/browser.min.js"></script>
    <link rel="stylesheet" href="styles.css" >
  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      const merge = (x, y) => Object.assign({}, x, y)
      class GameDisplay extends React.Component {
        constructor(props) {
          super(props)
          this.state = { 
            fill: props.primaryFill,
            secondsElapsed: 0 
          }
          this.tick = this.tick.bind(this)
          this.colorChange = this.colorChange.bind(this)
        }

        tick() {
          this.colorChange();
          this.setState((prevState) => merge(prevState, {
            secondsElapsed: prevState.secondsElapsed + 1,
          }));
          setTimeout(this.colorChange, 250)
          setTimeout(this.colorChange, 500)
          setTimeout(this.colorChange, 750)
        }

        colorChange() {
          this.setState((prevState, props) => {
            const { primaryFill, secondaryFill } = props
            const oldFill = this.state.fill
            const fill = oldFill === primaryFill ? secondaryFill : primaryFill
            return merge(prevState, { fill })
          })
        }

        componentDidMount() {
          this.tick()
          this.interval = setInterval(this.tick, 1000);
        }

        componentWillUnmount(){
          clearInterval(this.interval);
        }

        render() {
          return (
            <div>
              <h1>Seconds Elapsed: {this.state.secondsElapsed}</h1>
              <svg id="main_disp" width="300" height="300">
                <circle cx="150" cy="150" r="50" fill="black" />
                <circle id="heart" cx="150" cy="150" r="30" fill={this.state.fill} />
              </svg>
            </div>
          );
        }
      }

      function App() {
        return (
          <div>
            <GameDisplay primaryFill="red" secondaryFill="green" />
          </div>
        )
      }

      ReactDOM.render(<App />, document.getElementById("root"));
    </script>
  </body>
</html>

Some highlighted best practices:

  1. don't mutate the DOM, react favors a unidirectional flow of data, as in action > state > view, see https://medium.com/@khbrt/react-unidirectional-data-flow-explained-71bc35858226 (there are exceptions to this for intensive animations but as a general rule try to avoid it)
  2. in case you have to mutate it, try to get elements using the refs API instead of document.getElementById, see https://facebook.github.io/react/docs/refs-and-the-dom.html
  3. use functional components if there are no reasons for class ones, see https://facebook.github.io/react/docs/components-and-props.html
  4. code may get cleaner if you use some ES6+ features, see https://babeljs.io/blog/2015/06/07/react-on-es6-plus
Sign up to request clarification or add additional context in comments.

1 Comment

Mehiel thank you very much for your time and the references, this is a big help. Thank you.

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.