paxous
paxous

Reputation: 169

Nodejs variable in setInterval is changing and and giving asynchronous javascript the wrong value

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.

Upvotes: 0

Views: 31

Answers (1)

zumm
zumm

Reputation: 302

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);

Upvotes: 1

Related Questions