I want to call API’s every x second and this is what i have so far and was hoping suggestions of critique could help me out a lot.
function sendApiRequest() {
fetchData(); // this function will make API calls and inside this is a call for function that
//processes the data
console.log("Sending API request at " + new Date());
}
// Set the interval (in milliseconds) for sending API requests
const interval = 30000; // 30000 milliseconds = 30 seconds
// Set up the interval to call the function
//const intervalId = setInterval(sendApiRequest, interval);
setInterval(sendApiRequest, interval);
Also on some online sources i noticed that setInveral() call is assigned to a variable?
It depends on the context, but I did choose to move similar tasks to a separate server. A cron server. The main reason for a separate server is to reduce the load on the web server.
This is only important if you want to cancel the timer. E.g.:
// Set an interval to log a message every second
const intervalId = setInterval(() => {
console.log("Hello, World!");
}, 1000);
// Set a timeout to cancel the interval after 5 seconds
setTimeout(() => {
clearInterval(intervalId);
console.log("Interval has been cleared.");
}, 5000);
This will output:
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Interval has been cleared.
If you don’t intend to clear the timer, you don’t need to worry about assigning it to a variable.
I don’t intend to cancel the interval. My goal is when user lands up on the page to be
shown fresh status of call center agent being offline and online. I guess it will get cancelled once the user closes the page.
Hi @Stribor45, one suggestion would be to schedule the next request only after the previous one is completed; this way you’ll avoid race conditions if one request takes longer than the given interval. E.g., assuming fetchData() returns a promise: