0

I am trying to create a blinker in React, however, the blinker itself blinks / renders at an inconsistent rate and acts somewhat frustratingly. Please see the attached snippet. Is there something I am doing wrong with the component mounting? Thanks!

class Blinker extends React.Component {
  constructor(props) {
    super();
    this.state = {
      appear: true
    }
    this.blinker = this.blinker.bind(this);
  }

  blinker()  {
    this.setState({appear: !this.state.appear });
  }

  componentDidMount() {
    setInterval(this.blinker, 1000)
  }

  componentDidUpdate() {
    setTimeout(this.blinker, 1000)
  }

  render() {
    return (
      <div>
        { (this.state.appear) && "xxx" }
      </div>
    );
  }
}

ReactDOM.render(
  <Blinker />,
  app
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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="app"></div>
Jimmy
  • 3,090
  • 12
  • 42
  • 99

1 Answers1

3

Remove the componentDidUpdate. Why would you trigger a new one second timeout after your component updates? The interval from didMount will still be running.

Additionally, you need to clear the interval when your component unmounts:

componentDidMount() {
  this.blinkerId = setInterval(this.blinker, 1000)
}

componentWillUnmount() {
  clearInterval(this.blinkerId);
}
Andy Ray
  • 30,372
  • 14
  • 101
  • 138