I have a timer stored in an object inside a React component. What I try to do is cancel the timer before the component gets unmounted. Will my code work? How can I check it?
Constructor of the component:
constructor() {
super();
this.formRef = React.createRef();
this.redirectTimer = {
timer: () => {
setTimeout(() => {
this.props.history.push("/");
}, TIME_UNTIL_REDIRECT)
}
};
}
Call of clearTimeout:
componentWillUnmount() {
clearTimeout(this.redirectTimer.timer);
}
setTimeout returns the unique ID of the timer. You should store it and use it to clear the timeout.
constructor() {
super();
this.formRef = React.createRef();
this.timerID = null;
this.redirectTimer = {
timer: () => {
this.timerID = setTimeout(() => {
this.props.history.push("/");
}, TIME_UNTIL_REDIRECT)
}
};
}
componentWillUnmount() {
clearTimeout(this.timerID );
}
that is not the proper way to clear a timeout, the clearTimeout function expects an id of a timer, and the function setTimeout returns that id, in your case you have the object:
{
timer: () => {
setTimeout(() => { this.props.history.push("/");}, TIME_UNTIL_REDIRECT)
}
}
basically when you execute timer() it will run the function, but you are not storing the timerId on any place.
your code will clear the timeout with something like this:
constructor() {
super();
this.formRef = React.createRef();
this.timerId;
this.redirectTimer = {
timer: () => {
this.timerId = setTimeout(() => {
this.props.history.push("/");
}, TIME_UNTIL_REDIRECT)
}
};
}
////// other code
componentWillUnmount() {
clearTimeout(this.timerId);
}
you can test that with your code you are not clearing the timeout if you put a console.log inside the timeout, if you leave the page at some point you will see something logged, this is because the timer was running.... with the same test you can check with the fixed code that it will not log anything.