Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple purpose-specific setintervals or a single super interval

For code practice and improvement purposes I am writing a simple game (currently writing it generic enough to be a game engine).

I currently have numerous setInterval calls running, namely each "entity" (prefab/player) looking at keys held down, checking for collisions, updating position references etc. I was just wondering what sort of performance issues (if any) could arise from a high number of separate setIntervals. Their timing in relation to each other isn't important, so I'm not worried about them falling out of sync (they have slightly different intervals anyway), but would a single setInterval that loops through all entities to run all the checks actually be more efficient? My only worry with that option, is that the function could take longer than the interval time. Does creating new intervals create enough stress to be worrying about, when each one does quite a small amount?

like image 233
MDEV Avatar asked Mar 17 '26 03:03

MDEV


1 Answers

First of all, I wouldn't use setInterval since the callbacks could potentially stack up and occur one after the other if the code within the callback takes longer to execute than the interval.

As for having multiple timers, I do not think that it's a good idea, even if you do not care about synchronization. It makes the overall thing way too complex to maintain and would become a nightmare if you wanted to regulate your game speed. I would definitely go for a single timer.

Also, if you aren't aware aleady, there's the requestAnimationFrame function that's optimized for performing animations so you could use that instead of setTimeout. It will basically get called at 60fps if the browser can keep up.

You can use the timestamp passed as argument to the callback function passed to requestAnimationFrame to determinte how much time was elapsed since the last game loop iteration.

like image 175
plalx Avatar answered Mar 19 '26 16:03

plalx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!