I need the ('http://localhost:3000/users') to be updated in realtime when the server is running. I have a function fetchSlots() running in a given setInterval. If any user added or deleted in the DB (i.e in the ('http://localhost:3000/users')).I need to fetch the newly added item and use it in the fetchSlots().Like if I run the server for the below code,it is fetching details every 30000ms.If I add a user to the db ,in the next interval,Newly added user details is not fetched .similary,if I remove a user from the db while the server is running,in the next interval that deleted user details also being fetched.Should I have to reset the interval after every 30000ms or how can I solve this issue.
Any help!
async function polling() {
await axios.get('http://localhost:3000/users').then(async response => {
for (let l = 0; l < response.data.length; l++) {
slotFound = false;
const apiCall = setInterval(async () => {
await fetchSlots(response.data[l].pincode, response.data[l].emailid);
}, 30000);
}
});
}
to answer your title question : "How to reset the setInterval() in Js?" you can stop the interval by calling clearInterval with what setInterval returned.
clearInterval(apiCall);
but to do what you state in your description i feel like this would be much more straightforward.
async function polling() {
const response = await axios.get('http://localhost:3000/users');
for (let data of response.data) {
slotFound = false;
await fetchSlots(data.pincode, data.emailid);
}
}
setInterval(polling, 30000);