shubham agrawal shubham agrawal - 4 years ago 300
React JSX Question

How to stop setTimeout onClick in Reactjs

I am new to

Reactjs
and while using
setTimeOut
I got stuck on what is the best way to stop it.Should I use
clearTimeOut
or
stopPropagation()
.

This is my code

render: function() {
return ( < div className = "colorClick"
style = {
{
background: this.state.bgColor
}
}
onClick = {
this.detectColor
} > < /div><br/ >
);
},
calcTime: function() {
var time = Math.floor((Math.random() * 9) + 1);
this.setState({
total_time: time
}, () => {
window.setTimeout(this.calcTime, 250)
});
},


detectColor: function(event) {
window.clearTimeout(this.state.total_time);
window.clearTimeout(this.calcTime);
},


componentDidMount: function() {
this.calcTime();
},
componentWillUnmount: function() {
this.detectColor();
}


In this code I am using
clearTimeOut
but it is not working.I want that when I click on
div
with
className="colorClick"
, the setimeOut should clear and reset.

Answer Source

There are some bad practices in your code. I'll comment in the code the changes. Also, I'm guessing you are using React.createClass, which is deprecated.

Use the class syntax instead. and like Horia said, you need to store the timeout in a variable, so the entire code would look something like this:

import React from 'react'
class MyComponent extends React.Component {

  // notice no ":" and no "function"
  render () {
    return (

      <div {/* no space between "<" and the div */}
        className="colorClick" {/* no space around "=" */}
        style={ { background: this.state.bgColor } } {/* no space around "=" */}
        onClick={ this.clearTimeout } {/* no space around "=" */}
      /> {/* div is self closing, use this when there's no childs */}
    );
  } // no ","

  calcTime () {
    // use const if variable is not reassigned
    const time = Math.floor((Math.random() * 9) + 1);
    this.setState({
      total_time: time
    }, () => {
      // assign timeout to component property
      this.timeout = window.setTimeout(this.calcTime, 250)
    });
  }

  // no "event" passed as an argument since its:
  // 1. unnecessary
  // 2. doesn't exit when called in componentWillUnmount
  // method name changed to clearTimeout since it's more accurately describe what it does
  // notice fat arrow syntax to bind clearTimeout context to the class
  clearTimeout = () => {
    // use clearTimeout on the stored timeout in the class property "timeout"
    window.clearTimeout(this.timeout);
  }

  componentDidMount () {
    this.calcTime();
  }

  componentWillUnmount () {
    this.clearTimeout();
  }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download