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

setInterval中Node.js变量值变更导致异步JS获取错误值问题

解决异步IP变量被覆盖的问题

核心问题是异步请求util.status的回调执行时,外部的ip变量已经被后续的generateIp()赋值覆盖,导致回调里拿到的IP并非当时发起请求的那个。以下是两种直接有效的解决方式:

方式一:用局部变量保存当前IP

每次在定时器回调里生成IP后,将其存为局部变量,确保异步回调引用的是当前请求对应的IP:

// Ping our server
const options = {
  timeout: 1000 * 5,
  enableSRV: true,
};

let timeOutCount = 0;
setInterval(() => {
  const currentIp = generateIp();
  util.status(currentIp, 25565, options)
    .then((res) => {
      fs.appendFileSync('ips.txt', currentIp + '\n');
      console.log(`We've got one bois:\n${JSON.stringify(res, null, 2)}\nAt ip: ${currentIp}`);
    })
    .catch(() => timeOutCount += 1);
}, speed);

方式二:用立即执行函数绑定IP

通过立即执行函数将当前IP传入独立作用域,避免变量被后续修改影响:

// Ping our server
const options = {
  timeout: 1000 * 5,
  enableSRV: true,
};

let timeOutCount = 0;
setInterval(() => {
  const currentIp = generateIp();
  (function(ipToCheck) {
    util.status(ipToCheck, 25565, options)
      .then((res) => {
        fs.appendFileSync('ips.txt', ipToCheck + '\n');
        console.log(`We've got one bois:\n${JSON.stringify(res, null, 2)}\nAt ip: ${ipToCheck}`);
      })
      .catch(() => timeOutCount += 1);
  })(currentIp);
}, speed);

额外优化建议

fs.appendFileSync是同步IO操作,会阻塞Node.js事件循环,高频率请求下可能影响性能,建议替换为异步版本:

// 修改then回调中的文件写入逻辑
.then((res) => {
  fs.appendFile('ips.txt', currentIp + '\n', (err) => {
    if (err) console.error('写入IP失败:', err);
    console.log(`We've got one bois:\n${JSON.stringify(res, null, 2)}\nAt ip: ${currentIp}`);
  });
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 17:36:12