Desired Outcome: I am getting a script's status from an API and then checking what the status is. If the status = 'XYZ', I need to call the getStatus function again (using setInterval), else I just need to return/do nothing.
Issue: The major issue is that clearInterval() is not working and the getStatus() function is getting called after the mentioned interval (10 seconds here) again and again, EVEN THOUGH the status IS NOT EQUAL to 'XYZ'.
Please help out. Thanks in advance.
const [intervalId, setIntervalId] = useState();
useEffect(() => {
getStatus();
}, []);
const getStatus = async () => {
await getScriptStatus()()
.then(response => {
if (response.data[0].status == 'XYZ') {
setIntervalId(
setInterval(() => {
getStatus();
}, 10000)
);
}
else
return () => clearInterval(intervalId);
})
.catch(error => {
errorMessage(error);
});
CodePudding user response:
Use setTimeout instead of using setInterval.
For more details visit : Documentation on setTimeout
CodePudding user response:
Main problem here is most probably that you are installing new intervals recursively: function installs interval that calls function that installs interval etc, effectively producing cascade of intervals. These are more or less in-revocable, because their IDs live ephemerally in function scope that installed them and are then thrown away.
You can observe it with slightly modified version of your code in this sandbox.
CodePudding user response:
Change return () => clearInterval(intervalId);
to this clearInterval(intervalId);
.