简体   繁体   中英

How can I cancel the setTimeout time in react

I have created an application in which when a button is pressed the clock time starts. If nothing is done after 23 seconds (23000) is set to 0 and the state is changed (this.state.user) .This is correct.

If you click on the element again, I need the 23 seconds (23000) to be zeroed and the Timeout cleaned. Because if there is still some time left in the timeout, the item closes automatically.

I tried "clearTimeout (this.change); clearInterval (this.change); "but it doesn't work, I don't know how to cancel this time.

class Header extends Component {
    constructor(props) {
        super(props);

        this.change = null;

        this.state = {
            usuario: true,
            timeElapsed: 0,
            adminOrWrap: true,
        };

        ["descansoAdminWrap", "otrosDescansos",].forEach((method) => {
            this[method] = this[method].bind(this);
        });
    }

   componentDidUpdate(prevProps, prevState) {
        if (prevProps.notInCall === false && this.props.notInCall && this.state.usuario === true) {
            this.descansoAdminWrap(prevProps, prevState);
       }
   }

    descansoAdminWrap(prevProps){
        var usuarioAdminOrWrapFalse=  this.state.usuario && this.props.adminOrWrap === false;
        var notInCallFalseUsuario= this.props.notInCall === false && this.state.usuario
        //mostrar y ocultar el descanso de 'tiempo administrativo' y 'wrap time'
        if(this.state.usuario && this.props.notInCall){
            this.setState({
                usuario: false,
                timeElapsed: 0,
            });
            clearTimeout(this.change);
            clearInterval(this.change);
            if(prevProps.notInCall === false){
                this.handleAdminOrWrap(false)
                this.setState({
                    usuario: false,
                    timeElapsed: 0,
                });
                this.change = setTimeout(() => {
                    this.setState({
                        usuario: true,
                        notInCall: true,
                    });
                    this.handleAdminOrWrap(true)
                }, 23000)
            }
        }
    }

clearTimeout is used for setTimeout , and clearInterval for setInterval .

So using a clearInterval here isn't going to help.

I would check if you are actually call the clearTimeout with a console.log inside your if condition when you expect to do so. Especially when you are modifying the state.usuario value to false the first time around, which would prevent you to clear the condition again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM