简体   繁体   中英

JS setInterval is being called multiple times

I'm having following code

if (input.isValidLink()) {
  store()
    .then(db => db.update(message.from, text, json))
    .then(value => value.selectAllFromDB())
    .then(users => makeRequest(users));
}

Amd makeRequest function

makeRequest(user) {
  setInterval(() => {
    users.forEach(user => {
      httpRequest(user.json);
    });
  }, 10000);
}

What I'm trying to do, is selectAllFromDB function returns array of users from db, and it passed as argument to makeRequest function , which is looping thru each user, send request to receive json data and do it each 10 seconds, so it will not miss any changes. Each time when any user send the link, it should also start watching for this link. Problem is that on each received link it calls makeRequest function which creates another interval and if two links were received, I'm having two intervals. First looping thru this array

[{
  id: 1234,
  json: 'https://helloworld.com.json',
}]

And second thru this

[{
  id: 1234,
  json: 'https://helloworld.com.json',
}, {
  id: 5678,
  json: 'https://anotherlink.com.json',
}]

Is there any way this can be fixed so only one interval is going to be created?

You need to do something like this to make sure you only create one interval and are always using the latest users list:

let latestUsers;
let intervalId;
const makeRequest = (users) => {
  latestUsers = users;

  if (!intervalId) {
    intervalId = setInterval(() => {
      latestUsers.forEach(user => {
        httpRequest(user.json);
      });
    }, 10000);
  }
}

If you don't want variables floating around you can use a self-invoking function to keep things nicely packaged:

const makeRequest = (() => {
  let latestUsers;
  let intervalId;
  return (users) => {
    latestUsers = users;

    if (!intervalId) {
      intervalId = setInterval(() => {
        latestUsers.forEach(user => {
          httpRequest(user.json);
        });
      }, 10000);
    }
  }
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM