思路
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2c976319980350bf0505bde03117862e.png)
代码
const retryUrls = function (urls, timeout, callback, repeat = 0, index = 0, retryCount = 0) {
if (!Array.isArray(urls)) return
if (index >= urls.length) {
if (retryCount < repeat) {
index = 0
retryCount += 1
} else {
return
}
}
let timer = setTimeout(() => {
nextStep()
}, timeout)
const nextStep = () => {
stopTimer()
this.retryUrls(urls, timeout, callback, repeat, index + 1, retryCount)
}
const stopTimer = () => {
if (timer) {
clearTimeout(timer)
timer = null
}
}
callback(urls[index], stopTimer, nextStep, timeout)
}
示例
retryUrls(['https://test.com', 'https://baidu.com'], 5000, (url, stopTimer, nextStep) => {
$.ajax({
url,
method: 'GET',
success: () => {
stopTimer()
},
error: () => {
nextStep()
}
})
})