You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript Fetch中检测响应超时并触发提示(无需setTimeout和AbortController)

问题

希望实现:当使用JavaScript的Fetch发送请求耗时超过20秒时,弹出提示告知用户API异常,让用户刷新页面或稍后再试。要求不能使用setTimeout和AbortController,仅通过检测响应相关逻辑触发提示(类似通过response.status判断状态的方式)。

当前代码如下:

const envSoli = async () => {
    try {
      let peticion = await fetch("data.php", {
        method: "POST",
        body: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
        headers: { "Content-type": "application/x-www-form-urlencoded" },
        cache: "no-cache"
      });
      let oreen = await peticion.json();

        switch (oreen.enviando) {
          case -1:
              chenille++;
              document.getElementById("div1").append(oreen.cat + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
  
          case 1:
              chenille++;
              document.getElementById("div1").append(oreen.dog + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
        
          case 2:
                chenille++;
                document.getElementById("div2").append(oreen.sky + "<br />");
                nieva++;
                updateProgress(chenille, leray.length);
                tvmit_dieUp();
                break;
  
          case 3:
              chenille++;
              document.getElementById("div3").append(oreen.water + "<br />");
              tvmit_liveUp();
              updateProgress(chenille, leray.length);
              break;
      }
  
        OKTY(leray, chenille, aarsh, nieva);
      return true;
    } catch (error) {
      console.log(error)
    }
  }
  envSoli();
解决方案

Fetch API的Response对象本身没有直接提供请求耗时的属性,但可以通过记录请求发起和响应返回的时间戳计算耗时,以此判断是否超过20秒,完全不需要用到setTimeout或AbortController。

具体修改逻辑:

  • 在调用fetch前记录开始时间戳
  • 拿到响应后计算时间差
  • 如果时间差超过20秒(20000毫秒),弹出提示

修改后的代码如下:

const envSoli = async () => {
    try {
      // 记录请求开始时间
      const startTime = Date.now();
      
      let peticion = await fetch("data.php", {
        method: "POST",
        body: "ajax=1&do=check&lista=" + encodeURIComponent(leray[chenille]),
        headers: { "Content-type": "application/x-www-form-urlencoded" },
        cache: "no-cache"
      });
      
      // 计算请求耗时并判断是否超时
      const requestDuration = Date.now() - startTime;
      if (requestDuration > 20000) {
        alert("API响应超时,请刷新页面或稍后再试");
        return false;
      }
      
      let oreen = await peticion.json();

        switch (oreen.enviando) {
          case -1:
              chenille++;
              document.getElementById("div1").append(oreen.cat + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
  
          case 1:
              chenille++;
              document.getElementById("div1").append(oreen.dog + "<br />");
              updateProgress(chenille, leray.length);
              tvmit_wrongUp();
              break;
        
          case 2:
                chenille++;
                document.getElementById("div2").append(oreen.sky + "<br />");
                nieva++;
                updateProgress(chenille, leray.length);
                tvmit_dieUp();
                break;
  
          case 3:
              chenille++;
              document.getElementById("div3").append(oreen.water + "<br />");
              tvmit_liveUp();
              updateProgress(chenille, leray.length);
              break;
      }
  
        OKTY(leray, chenille, aarsh, nieva);
      return true;
    } catch (error) {
      console.log(error)
      // 请求彻底失败时也弹出提示
      alert("API请求异常,请刷新页面或稍后再试");
    }
  }
  envSoli();

补充说明:

  • 这种方式是在响应返回后才做耗时判断,不会主动中止请求,但符合你“通过检测响应逻辑触发提示”的要求
  • 进入catch块时(比如网络断开)也添加了提示,覆盖更多异常场景
  • 时间差精确到毫秒,requestDuration > 20000对应20秒的超时阈值

内容的提问来源于stack exchange,提问作者SadDeepLoper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 18:10:29