Reputation: 141
I'm trying to clear setInterval with calling clearInterval. however, i call setInterval function inside function. So I'd like to trigger the parameter in the setInterval by clearInterval, But i do not know how to get reach this thing. And what i say is confusing so I just want to show u the code :
function getAPI() {
const polling = () => {
if (convert !== undefined) {
axios
.post("/realtime", {
GET_API_URL: convert.GET_API_URL,
Headers1_key: convert.Headers1_key,
Headers1_Value: convert.Headers1_Value,
Headers2_key: convert.Headers2_key,
Headers2_Value: convert.Headers2_Value,
Headers3_key: convert.Headers3_key,
Headers3_Value: convert.Headers3_Value,
})
.then(response => {
setRandom(response.data);
})
.catch(error => {
console.log(error);
});
} else {
alert("try again.");
}
};
setInterval(polling, convert.API_Read_Speed);
}
const init = () => {
clearInterval(polling); // i want to call polling and i want to stop the axios posting
};
Upvotes: 0
Views: 350
Reputation: 448
according to your comment seems like you need to stop the polling in react.
you can use the useRef
hook to keep the reference of the interval and clear it whenever you like.
useEffect(() => {
interval.current = setInterval(() => {
...
}, ms)
}, [input]);
const closeConnection = () => {
clearInterval(interval.current);
}
Upvotes: 4
Reputation: 2525
You can store setInterval
inside a variable and access it like that.
Example:
let interval;
function foo() {
interval = setInterval(() => {
...
}, ms)
}
function bar() {
clearInterval(interval);
}
Upvotes: 3