How to clearInterval of the function that has started and running with setInterval?

55 Views Asked by At

how to stop the loadFriendList when setWorker Value is"0"?

const [worker, setWorker] = useState('1');
 
function start() {
 setInterval(loadFriendList,5000);
}
useEffect(start, []);
 
function n() {
  setWorker("0");
  Alert.alert('check', worker);
}
2

There are 2 best solutions below

0
Shankaja Aroshana On BEST ANSWER

Don't use strings as number it's an unnecessary hassle .

use useRef hook to store intervalID .

This useEffect hook fires whenever worker is change.

see inside the [] we've added worker variable. It's called dependancy array. Basically you're saying to useEffect look on these variables and fire if anything changes

useEffect(() => {
  if(worker == 0) intID.current && clearInterval(intId.current)
},[worker])

The useRef hook is holding on to the Interval you set up when page loading, to uniquely identify and run methods like clearInterval() in future

Finally It Should Look Like

const [worker, setWorker] = useState(1);
const intId = useRef(null)
 
useEffect(() =>{
  intId.current = setInterval(loadFriendList,5000);
  return () => clearInterval(intId.current)
}, []);
 
useEffect(() => {
  if(worker == 0) intId.current && clearInterval(intId.current)
},[worker])
0
Hardik Mandankaa On
const [worker, setWorker] = useState('1');
const [intervalId, setIntervalId] = useState(null);

function start() {
  setIntervalId(setInterval(loadFriendList, 5000));
}

useEffect(start, []);

function n() {
  setWorker("0");
  clearInterval(intervalId);
  Alert.alert('check', worker);
}