user9645391
user9645391

Reputation:

How to clearTimeout a setTimeout in another function in React JS?

I have something like this:

  redTimeout = () => {
    setTimeout(() => {
      this.props.redBoxScore();

      this.setState({
        overlayContainer: 'none'
      });

    }, 5000);
  }

And I have a method runs when a button is clicked:

  handleTerminate = () => {

  }

How can I stop the setTimeout in the another function when the button is clicked?

Upvotes: 0

Views: 347

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370779

Put the timeout ID returned by setTimeout into state or a ref or something so that you can reference it in the other function:

redTimeout = () => {
  const timeoutId = setTimeout(() => {
    this.props.redBoxScore();
    this.setState({
      overlayContainer: 'none'
    });

  }, 5000);
  this.setState({ timeoutId });
}
handleTerminate = () => {
  clearTimeout(this.state.timeoutId);
}

Upvotes: 2

Related Questions