When using setInterval
, you have as much time as you've specified for the interval parameter, to do the work. It's not a "blocking" wait, the timer runs in parallel with your code. So just set it to something safe, like 2 or 3 seconds. That's your period in which you can get things done. This is how all JS games work. You should be able to test this easily in the browser, just set up a small program that adds a million numbers in place of your 2-second task, have it run every n
seconds, and see how that affects setInterval
's firing. EDIT I think what you'll find (if you write a very simple test) is that if you have something that is blocking for 2 seconds, but your interval is set to 1 second, then yes, as soon as your first function call completes it's going to jump straight into the second one (because it will have already backed up), but the timer will fall further and further behind. In any real time application, you have to be able to guarantee that work is going to be completed within some maximum time period. This is not an option. For more information, read up on Gaffer's Fix Your Timestep which discusses issues of timing in detail.
It shouldn't be taking you that long to process anything in a game (client or server). If it is, then your code is either highly inefficient or it needs to be broken up into individual "tasks" with higher granularity, which can then be fed into the function. That way, you'd have no problems with setInterval
. Just a thought.
Just to add... It seems to me that if you tell us what you are trying to achieve, we can help you find the best solution. Right now, I'm feeling that what you're attempting is missing the mark.