I am currently building an endpoint to process a large amount of data. However I am running into an error over running out of resources. I'm pretty sure the issue is the fact that I am making too many request to the server without limiting it. However every attempt to throttle it has been unsuccessful. So I'm looking at how I can throttle my asynchronous endpoint and avoid this issue.
- SPECIFIC ERROR net::ERR_INSUFFICIENT_RESOURCES
Code
const sendStepData = async() =>{
try{
const body = {a,b,c,d,e,f}
assignToBody(body)
const response = await fetch('http://localhost:5000/stepdata',{
method:"POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body)
})}catch(err){
console.log(err.message)
}
}
Even after adding a SetTimeOut I am unable to throttle the endpoint.
Code with timeout
const sendStepData = async() =>{
try{
const body = {a,b,c,d,e,f}
assignToBody(body)
const response = await fetch('http://localhost:5000/stepdata',{
method:"POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(body)
})}catch(err){
console.log(err.message)
}
}
const delayQue = () =>{
setTimeout(sendStepData,5000)
}
One thing to clarify as well that may be helpful. This endpoint is in a separate file that I call after I have prepped my data to be passed to my db.
I'll even take suggestions at material to look at if it may help. Thank you for your time.
CodePudding user response:
You need to debounce your method :
let now = Date.now();
const delayQue = () =>{
if(Date.now() - now > 5000) {
now = Date.now();
sendStepData()
}
}
it will only make the call if 5000ms has passed since the last call, and it will wait 5000ms before the first call also.
You can also wait for the 5000ms to pass and call the method
let now = Date.now();
let timeoutId = null;
const delayQue = () =>{
if(Date.now() - now > 5000) {
now = Date.now();
sendStepData()
} else if(!timeoutId) {
timeoutId = setTimeout(() => {
now = Date.now();
sendStepData();
timeoutId = null,
}, 5000 - (Date.now() - now))
}
}
you could look for the lodash debounce method also, if you don't want to do it yourself, and have a more complete solution