[英]how can i add a for loop to stop infinite loop
i want to make this code keep trying after getting an error for like 10 times after the 10 times it should stop trying and instead of trying it will show a message instead that there is something wrong, so i threw an error there on purpose to make it give errors and a for loop but instead it keeps trying in separate error messages as shown in the pic below, so how can i add that for loop so it can stop trying running the function and show a message instead?我想让这段代码在出现错误 10 次后继续尝试,在 10 次之后它应该停止尝试而不是尝试它会显示一条消息而不是有问题,所以我故意在那里抛出一个错误它会给出错误和一个 for 循环,但它会继续尝试单独的错误消息,如下图所示,那么我如何添加那个 for 循环,以便它可以停止尝试运行 function 并显示一条消息?
this is my code:这是我的代码:
async function getQuote() {
loading();
const apiUrl = 'https://cors-anywhere.herokuapp.com/http://api.forismatic.com/api/1.0/?
method=getQuote&format=json&lang=en';
try {
const response = await fetch(apiUrl)
const data = await response.json();
// Changing the blank Author textfield to Unknown
if (data.quoteAuthor === ''){
authorText.innerText = 'Unknown';
} else {
authorText.innerText = data.quoteAuthor;
}
if (quoteText.innerText.length > 120){
quoteText.classList.add('long-quote');
} else {
quoteText.classList.remove('long-quote');
}
quoteText.innerText = data.quoteText
//Stop loader, Show Quote
complete();
throw new Error("Opss!")
} catch(error) {
for(let i=0; i < 10 ; i++){
getQuote();
// console.log('something went wrong!', error);
}
}
}
you can try building a global variable that counts the number of errors and breaks out of the loop at a certain number您可以尝试构建一个全局变量来计算错误的数量并在一定数量时跳出循环
async function getQuote(numOfTries = 1) {
try {
...
throw new Error("Opss!")
}
catch (error) {
if (numOfTries === 10) {
console.log('something went wrong!', error);
} else {
numOfTries++;
getQuote(numOfTries);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.