i am running a setinterval
function to check for a payment from coinbase in my react native app, i run the function after every 10 seconds, after the payment has been made, i clear the setinterval
and navigate to the homepage, but still the setinteval
keeps running how can i stop this?
useEffect(() => {
getData();
myinterval();
}, []);
const myinterval= () => setInterval(function () {
checkCharge();
}, 10000);
const stopCounter = () => {
clearInterval(myinterval);
}
const checkCharge = async () => {
try {
...SOME_CODE_HERE...
stopCounter()
navigation.navigate("HomeScreen");
} catch (e) {
console.log(e);
}
};
CodePudding user response:
I believe it's because myinterval
is assigned to a function and not the actual return value of the setInterval()
function. So try to change
const myinterval = () => setInterval(function () {
checkCharge();
}, 10000);
to
const myinterval = setInterval(function () {
checkCharge();
}, 10000);
and then canceling the myinterval
variable with clearInterval(myinterval);
CodePudding user response:
You aren't using the return from myinterval()
to clear the setInterval
. setInterval()
returns an id that is used to clear the interval. When you call the function myinterval
, it is returning that ID. What you need to do is store that ID in a variable that you can use to clear the interval.
...
function createInterval(){
return setInterval(checkCharge, 10000);
}
function stopCounter(id){
clearInterval(id);
}
...
var id = createInterval();
...
function checkCharge(){
try {
...
stopCounter(id);
...
} catch(e){
console.error(e);
}
}