Reputation: 6873
I just developed an JS game which has too many setIntervals to function calls. The intervals are creating the flicker effect which is not acceptable. I wanted to check with experts if can I anyhow make it smooth adopting alternative to setInterval calls which are smooth too?
Have a look at the game http://umairashraf.net23.net/booble/
Upvotes: 0
Views: 812
Reputation: 32112
I suspect your performance problem is that for every bubble, you create a new animator function that executes every 20ms. That is a lot of functions executing frequently.
You could improve performance by keeping all the bubbles in one data structure, and using one function, executing every 20ms, to update all of them at once.
Upvotes: 1
Reputation: 923
You have no "recursive calls". You have a lot of timers being created. For each new bubble you create a new timer! A hundred of callback functions are being fired every 20 ms! And within each of these calls you do
$(bubble).offset().top;
if (pos >= 0 - $(bubble).height()) {
$(bubble).css({ top: (pos - 1000) + "px" });
}
A jquery object is constructed (3 times!), its offset is calculated, its height is queried... A hundred of times, every 20 ms!
For each created bubble you should cache its jquery object and its current position. Keep them in arrays or hashes: bubbleJqueryObjects and bubblePositions. Make a single animateBubbles() callback, which will just update "top" css property of all existing bubbles at once. Save 5000 function calls, 15000 jquery object constructions and 5000 position\size queries. Every second.
Upvotes: 4
Reputation: 9965
You might look into the Composite design pattern. Its a popular design pattern for handling hierarchical type data and being able to query it in a fast way.
Upvotes: 1