Javascript 在设定间隔内等待
我有一个函数,可以执行一些Javascript 在设定间隔内等待,javascript,asynchronous,async-await,settimeout,setinterval,Javascript,Asynchronous,Async Await,Settimeout,Setinterval,我有一个函数,可以执行一些HTTP请求,如果触发某个条件,我需要经常每隔一定的时间(在本例中为5秒)执行这些请求 发生的情况是,有时setInterval循环内的请求花费的时间超过了指定的时间,循环再次触发,再次调用请求,而不等待前一个请求得到解决 function doRequests() { setInterval(async () => { //Sometimes the following line takes more than 5 se
HTTP请求
,如果触发某个条件,我需要经常每隔一定的时间(在本例中为5秒)执行这些请求
发生的情况是,有时setInterval
循环内的请求花费的时间超过了指定的时间,循环再次触发,再次调用请求,而不等待前一个请求得到解决
function doRequests() {
setInterval(async () => {
//Sometimes the following line takes more than 5 seconds to return its promise
const response = await myRequestFunction();
// do something with response...
if(/*certain condition is triggered*/)
{
//Call the function again
doRequests();
}
}, 5000);
}
doRequests();
我已经尝试过像post中那样的递归setTimeOut函数,它工作了,但是在几个请求之后它就停止了工作,不是因为发生了堆栈溢出,而是因为它停止了!请求已完成,但它从未返回响应,因此代码停止。在它停止前几次,它变慢了
我也尝试过在while循环中使用setTimeOut,但是循环似乎不等待间隔,而不是在这个异步上下文中
因此,我需要的解决方案是:每5秒执行一次请求,但如果返回响应所需的时间超过5秒,请等待响应。好吧,这里有一个解决方案,以尽可能保持周期最有规律。只要响应在5s超时内到达,循环轮询就应该是非常有规律的。但是,如果响应延迟,新请求将在处理后立即发出
我还添加了一个try-catch块,因为它很可能在HTTP请求上出现一些错误(同时还因为您正在执行其他操作)。这将引导您决定在这种情况下如何行事
async function doRequests() {
let answered = false;
let expired = false;
//start the timer
let tmr = setTimeout(function() {
if (answered) {
//response already received (and processed), so start a new request
doRequest();
}
else {
//mark the timer as expired
expired = true;
},
5000
);
try {
const response = await myRequestFunction();
// do something with response...
if(/*certain condition is triggered*/)
{
answered = true;
if (expired) {
//Call the function again
doRequests();
}
}
}
catch (err) {
//error trapped: clear timeout
clearTimeout(tmr);
if (/* decide to continue as it was fine */) {
answered = true;
if (expired) {
//Call the function again
doRequests();
}
}
}
}
doRequests();
使用setTimeout代替注意:您没有清除间隔,因此每次调用函数时都会创建越来越多的间隔。“请求已完成,但它从未返回响应”-修复此问题。您不能让它在下一次迭代之前等待响应,如果响应从未发生,则期望循环继续。请参阅或了解async
/wait
用法的正确示例我使用setTimeOut解决了它,我没有正确使用递归,因此它由于某种堆栈延迟而突然停止。但现在我知道怎么用了。谢谢你的回答:)