Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i replace a setTimeout function?

I want to set a timeout to go off X amount of seconds from now. If X changes, I want to clear the timeout and start a new timeout based on the new value of X. When I try to clear timeout it wont work. Here is my code

componentWillReceiveProps(nextProps) {
    if (this.props.expirationTimeout !== nextProps.expirationTimeout) {
      this.setState({ 
          expirationTimeout: nextProps.expirationTimeout 
      });
      window.clearTimeout(this.setExpiration);
      this.setExpiration(nextProps.expirationTimeout);
    }
}

setExpiration(time) {
    let timeouts = [];
    for (var i = 0; i < timeouts.length; i++) {
      clearTimeout(timeouts[i]);
    }
    var t = time - new Date().getTime();
    timeouts.push(setTimeout(this.state.logoutUserAndRedirect, t));
}
like image 309
Christopher Mellor Avatar asked Mar 28 '26 00:03

Christopher Mellor


1 Answers

  1. to use clearTimeout() you need id that setTimeout returned before
  2. currently result of setTimeout with id of timer is stored into block-level variable timeouts. So there is no chance to use it for clearTimeout in componentWillReceiveProps.
  3. Since every single change into state triggers re-rendering I suggest not storing props.expirationTimeout value into state. The same is for logoutUserAndRedirect. There is no sense to keep it in state.
  4. what if new value of timer is less than previous? what if according to new value you have already missed the time to do what you plan? setTimeout will work this way if it gets delay value < 0. Is not it great? :)
  5. [UPD] also I believe it's needed to store timestamp when recent timeout has started. This way we would be able to correct it later after delay value is changed.

    componentWillReceiveProps(nextProps) {
        if (this.props.expirationTimeout !== nextProps.expirationTimeout) {
            this.modifyExpiration(this.timerStartedAt + nextProps.expirationTimeout - this.props.expiration);
        }
    }
    
    modifyExpiration(time) {
        this.timeoutId && clearTimeout(this.timeoutId);
        this.timeoutId = setTimeout(this.logoutUserAndRedirect, time);
        this.timerStartedAt = +new Date();
    }
    
like image 177
skyboyer Avatar answered Mar 31 '26 04:03

skyboyer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!