uniapp实践里面的一个 数据请求优化代码,减少一段时间内的数据请求

100 阅读1分钟
// 优化性能,防止频繁数据请求用,后面有空写到组合函数里面去
const sendState = {
  requestCount : 0,      // 初始化次数状态
  isBlocked : false,     // 是否可以请求数据
  blockDuration : 10000, // 阻止再次请求的时间(10秒)
  requestTimeFrame : 5000, // 判断请求连续的时间范围(5秒)
  firstRequestTime : Date.now() // 记录第一次请求的时间戳
}
// 判断一段时间内是不是频繁请求数据
const lazyLoad = ()=>{
  if (sendState.isBlocked) {
    uni.showToast({ icon: 'none', title: '您的请求过于频繁! 请在10秒后再试' })
    return;
  }
  const currentTime = Date.now();
  // 检查距离第一次请求是否超过了5秒
  if (currentTime - sendState.firstRequestTime < sendState.requestTimeFrame) {
    // 如果请求次数超出阈值,显示提示,并且阻止进一步的请求
    sendState.requestCount += 1;
    if ( sendState.requestCount >= 5) { // 假设连续请求5次以上就触发提示
      uni.showToast({ icon: 'none', title: '请求次数过多,请稍后再试!' })
      // 设置为阻止状态
      sendState.isBlocked = true;
      // 30秒后重置状态,允许再次发送请求
      setTimeout(() => {
        sendState.isBlocked = false;
      },  sendState.blockDuration);
      // 复位请求计数和时间
      sendState.firstRequestTime = currentTime;
      sendState.requestCount = 0;
      return;
    }
  } else {
    // 5秒已经过去,重置请求计数和时间
    sendState.firstRequestTime = currentTime;
    sendState.requestCount = 1;
  }
// 发送数据
}