Home > Back-end >  Nodejs variable in setInterval is changing and and giving asynchronous javascript the wrong value
Nodejs variable in setInterval is changing and and giving asynchronous javascript the wrong value

Time:08-24

I have the code below:

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

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

  ip = generateIp();
}, speed);

And there's a five-second delay before a timeout error gets caught. The thing is, because of the asynchronous javascript, the IP variable's value is changing in the span of those five seconds, in turn causing the variable to be inaccurate once the IP is to be verified as a server.

CodePudding user response:

Just put your ip generation into setInterval closure. Like that:

let timeOutCount = 0;
setInterval(() => {
  const ip = generateIp();
  util.status(ip, 25565, options)
    .then((res) => {
      // ...
    })
    .catch(() => timeOutCount  = 1);
}, speed);
  • Related