NodeJS SetInterval with Async/Await

Viewed 230

I'm using the following code with a websocket to scrape data from a DB and return to users. It returns chat messages, users status and other things. The code works as expected (in testing) but I have a couple of questions.

                setInterval(async () => {
                    if (connectedUserIDs.length > 0) {
                        logger.info("short loop...")
                        await eventsHelper.extractEvents(db, connectedUserIDs, connectedSockets, ws)
                    }
                }, 5000)

Question 1. Will the SetInterval wait for the the "await" or will it just fire every 5 seconds? I assume it will fire every 5 seconds regardless.

If that is the case.

Question 2. Is there a way to repeat a task like above but ensure it only re-runs if the previous run as completed with a minimum time of 5 seconds? I want to avoid a situation where I get multiple queries running at the same time. Maybe the setInterval could be cancelled and restarted each time...

thankyou Adam

1 Answers

Question 1. Will the SetInterval wait for the the "await" or will it just fire every 5 seconds? I assume it will fire every 5 seconds regardless.

Yes it will naively re-run every 5s

Question 2. Is there a way to repeat a task like above but ensure it only re-runs if the previous run as completed with a minimum time of 5 seconds

Easiest way to prevent collisions is to set the next run after the await:

let timeoutId;
const extractEvents = async () => {
  if (connectedUserIDs.length > 0) {
    logger.info("short loop...");
    await eventsHelper.extractEvents(db, connectedUserIDs, connectedSockets, ws);
  }
  timeoutId = setTimeout(extractEvents, 5000);
};
timeoutId = setTimeout(extractEvents, 5000);

Storing timeoutId so you can clear it later

Related