js每隔2秒发送http自动请求10次不同id的信息请求完成后关闭
你可以使用setInterval函数来实现每隔2秒发送一次HTTP请求。在每次请求时,你可以通过添加不同的id参数来获取不同的信息。在发送完10次请求后,你可以使用clearInterval函数来停止定时器。以下是一个示例代码:
let counter = 0;
const maxRequests = 10;
const intervalId = setInterval(() => {
if (counter >= maxRequests) {
clearInterval(intervalId);
return;
}
const id = generateRandomId(); // 生成不同的id
const url = `http://example.com/api/info?id=${id}`;
// 发送HTTP请求
// 你可以使用任何你喜欢的HTTP库,比如fetch、axios等
fetch(url)
.then(response => response.json())
.then(data => {
// 处理返回的数据
console.log(data);
counter++;
})
.catch(error => {
// 处理错误
console.error(error);
counter++;
});
}, 2000);
function generateRandomId() {
// 生成一个随机的id
// 你可以根据你的需求来实现这个函数
return Math.floor(Math.random() * 1000);
}
请注意,上述代码中的fetch函数是ES6的内置函数,用于发送HTTP请求。如果你的浏览器不支持fetch,你可以使用其他HTTP库来发送请求,比如axios、ajax等
原文地址: http://www.cveoy.top/t/topic/hyA8 著作权归作者所有。请勿转载和采集!