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));
}
clearTimeout() you need id that setTimeout returned beforesetTimeout with id of timer is stored into block-level variable timeouts. So there is no chance to use it for clearTimeout in componentWillReceiveProps. props.expirationTimeout value into state. The same is for logoutUserAndRedirect. There is no sense to keep it in state.setTimeout will work this way if it gets delay value < 0. Is not it great? :)[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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With