Search code examples
javascriptreactjsecmascript-6blinker

Inconsistent Blinker speed in React


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>


Solution

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