写一个函数,对接口 examp 发出 n 次请求,要求除了第一次请求,往后每次请求都等待上次请求完成并等待50毫秒再进行请求,所有请求结束后,打印出结果。
已对请求进行封装如下:
const getData = function (url, callback) {
setTimeout(() => {
if ("function" === typeof callback) {
callback(+new Date())
}
}, +(Math.random() * 1000).toFixed())
}
// max 数量, time 间隔时间
const getData = function(max, time) {
let count = 0, // 累计次数
timer = null; // 定时器
const fn = function() {
// 发起请求,请求完成过后
console.log(count);
count++; // 数量累加
// 判断数量
if (count < max) {
// 满足条件开始定时
timer = setTimeout(() => {
// 清空定时器
clearTimeout(timer);
// 回收变量
timer = null;
// 递归,开始下一次
fn();
}, time);
} else {
// 不满足条件清空定时器和定时器变量
clearTimeout(timer);
timer = null;
}
}
fn();
}
getData(5, 1000);