DoneDeal
DoneDeal

Reputation: 159

How to clearInterval onClick while setInterval runs in componentDidMount?

I have a header whose background image can either change after a click or because of a setInterval loop.

The setInterval changes the image every 7 seconds, and is defined in componentDidMount.

When I click on a button to change the image, setInterval obviously doesn't care and keep running, so sometimes the user can't enjoy the new image more than a second.

How to reset setInterval when I click on a button? I can't write clearInterval() in my function handleClick(), because setInterval can't be accessed.

Upvotes: 0

Views: 62

Answers (1)

gazdagergo
gazdagergo

Reputation: 6691

Just save the interval into a class variable with this.interval so you can reach from anywhere.

class Header extends React.Component {
  componentDidMount(){
    this.interval = setInterval(nextImage, 7000);
  }

  handleClick = () => {
    clearInterval(this.interval);
    nextImage();
    this.interval = setInterval(nextImage, 7000);    
  }

  nextImage = () => {
    ...
  }

  render() {
    ...
  }
}

Upvotes: 1

Related Questions