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

setInterval最多执行10次即停止,伴NetworkError问题求助

问题分析与解决方案

核心原因

  1. 浏览器并发请求限制:多数浏览器对同一域名的并发HTTP请求有默认限制(通常是6-8个)。你的setInterval每秒发送一次请求,如果前一次请求因网络延迟、服务器处理慢等原因未完成,新请求会被排队,当队列达到浏览器上限后,后续请求会被阻塞,表现为停止发送,甚至触发NetworkError。
  2. 无节制的请求堆积:setInterval不会等待前一次请求的Promise完成,持续发送新请求,导致浏览器的HTTP连接池被占满,资源耗尽后浏览器会停止调度后续请求。
  3. 潜在的请求异常未处理:虽然你加了catch,但如果请求处于挂起状态(比如未设置超时),会一直占用连接,加剧并发限制问题。

解决方法

1. 改用递归setTimeout替代setInterval

确保前一次请求完成(无论成功或失败)后,再发送下一次请求,从根源避免并发堆积:

function sendRequest() {
    console.log('sending request')
    fetch(`/api/....`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
        },
        referrerPolicy: 'no-referrer'
    }).then((res) => {
        console.log('response received')
        console.log(res)
    }).catch((err) => {
        console.log(err)
    }).finally(() => {
        // 请求完成后,延迟1秒发送下一次
        setTimeout(sendRequest, 1000)
    })
}

// 启动请求
sendRequest()

2. 添加请求超时机制

通过AbortController给请求设置超时,避免请求长时间挂起占用连接:

function sendRequest() {
    console.log('sending request')
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), 5000) // 5秒超时

    fetch(`/api/....`, {
        method: 'POST',
        headers: {
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': 'application/json'
        },
        referrerPolicy: 'no-referrer',
        signal: controller.signal
    }).then((res) => {
        console.log('response received')
        console.log(res)
    }).catch((err) => {
        if (err.name === 'AbortError') {
            console.log('请求超时')
        } else {
            console.log(err)
        }
    }).finally(() => {
        clearTimeout(timeoutId)
        setTimeout(sendRequest, 1000)
    })
}

sendRequest()

3. 排查浏览器环境干扰

  • 禁用浏览器扩展(如广告拦截、代理工具),部分扩展会拦截高频请求。
  • 检查开发者工具的网络节流设置是否开启,避免人为限制请求频率。

4. 服务器端验证

确认服务器是否存在请求频率限制,或响应延迟过高的情况——即便服务器能返回响应,过长的处理时间也会导致客户端请求堆积。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:10:13