Home > Mobile >  Running thousands of setInterval functions in NodeJS simultaneously
Running thousands of setInterval functions in NodeJS simultaneously

Time:06-07

this is more of a code-less question as I don't think it's that important in regards to my question.

In short, I'm building an app where users create a profile. Every user has an amount of credits which they can use to promote their profile.

How the promotion works?

Each user has a "lastUpdated" field in the DB, after which they're sorted on the homepage. When a user triggers the promotion through an API call, I run a setInterval of X miliseconds (provided by the user).

Every X miliseconds, the user's "lastUpdated" field receives a timestamp and X credits are subtracted from their account. Once the user runs out of credits, the setInterval stops.

My acutal question(s)

How is this performance-wise, considering the fact that there could be thousands of those calls, resulting in thousands of setInterval functions running at the same time?

Is there any other way to approach this?

Thank you!

CodePudding user response:

It would be better to calculate everything on-demand when it's needed. Assuming the amount of credits used are dependent on how long the promotion has been showing for, you could store the start time in the database and then use the current time to calculate how many credits are remaining based on how long has elapsed. This would result in much less operations compared to running a function every few milliseconds.

CodePudding user response:

If you really have to do this with an interval, it would be best to just have one running every 5 seconds or so (random number). Since this is interfacing with the DB, that may be too much load.

Just doing things on demand when the API from one user comes in should be the cleanest option.

  • Related