I have this simplified code below. When the user clicks on CLICK ME it will start a 5 second interval that after that will doSomethingImportant(). It works well, except on the case someone clicks on another component (Toolbar, footer) that brings you to a different component. In that case, the interval will keep executing all the time. How can I prevent that from happening? So that when AnswerScreen is unmounted, the interval is cleared? The "trick" below doesn't work.
const AnswerScreen = (props) => {
const [timeout, setTimeout] = useState(false);
useEffect(() => {
return () => { clearInterval(timeout) }
}, []);
const itemClickHandler = (index, value) => {
setTimeout(setInterval(() => {
props.doSomethingImportant();
return () => { clearInterval(timeout) }
}, 5000));
}
return (
<div onClick={() => itemClickHandler(3, 4)}>CLICK ME</div>
);
}
export default connect(null, null)(AnswerScreen);
With
setTimeout
useclearTimeout
With
setInterval
useclearInterval
To clear the timeout when routing to another component
useEffect(()=>{
return () => clearTimeout(timeoutRef.current)
},[])
To clear previous timeout when user click the button 2 or more times
const AnswerScreen = (props) => {
const timeoutRef = useRef(null);
const itemClickHandler = (index, value) => {
if(timeoutRef.current) clearTimeout(timeoutRef.current)
timeoutRef.current=setTimeout(setInterval(() => {
//do what ever you want
props.doSomethingImportant();
}, 5000));
}
return (
<div onClick={() => itemClickHandler(3, 4)}>CLICK ME</div>
);
}