Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling update method vs having a setInterval

In my game engine, there are objects that need to be updated periodically. For example, a scene can be lowering its alpha, so I set an interval that does it. Also, the camera sometimes needs to jiggle a bit, which requires interpolation on the rotation property.

I see that there are two ways of dealing with these problems:

  1. Have an update() method that calls all other object's update methods. The objects track time since they were last updated and act accordingly.

  2. Do a setInterval for each object's update method.

What is the best solution, and why?

like image 336
corazza Avatar asked Jul 10 '12 22:07

corazza


People also ask

Why is setInterval not accurate?

why is setInterval inaccurate? As we know, setTimeout means to run the script after the minimum threshold (MS unit), and setInterval means to continuously execute a specified script with the minimum threshold value period. Note that I use the term minimum threshold here because it is not always accurate.

Does setInterval affect performance?

Yes it is. setTimeout & setInterval are asynchronous. setInterval won't wait until the request is done. It will keep on adding requests to do every second, but it will delay itself if it goes over 1 second.

Why is it important to store the value returned by the call to setInterval ()?

setInterval returns an ID which you can later use to clearInterval(), that is to stop the scheduled action from being performed.

Does setInterval execute immediately?

This property can be used in the callback of the setInterval() function, as it would get immediately executed once and then the actual setInterval() with this function will start after the specified delay.

What is difference between setInterval and setTimeout?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.


1 Answers

setInterval does not keep to a clock, it just sequences events as they come in. Browsers tend to keep at least some minor amount of time between events. So if you have 10 events that all need to fire after 100ms you'll likely see the last event fire well into the 200ms. (This is easy enough to test).

Having only one event (and calling update on all objects) is in this sense better than having each object set it's own interval. There may be other considerations though but for at least this reason option 2 is unfeasible.

Here is some more about setInterval How do browsers determine what time setInterval should use?

like image 118
Halcyon Avatar answered Sep 30 '22 02:09

Halcyon