puk
puk

Reputation: 16782

Javascript setInterval performance drop with multiple animations

I am using setInterval(foo,ms) to carry out an animation. I really don't want to post all the code for the animation here as it spans multiple files. It's basically a bunch of images falling. Every second I call ctx.drawImage(img,...) while updating the coordinates to simulate gravity.

I have divided the canvas into two sections, one animation on the left and one on the right. When one of them is activated the frame rate is stable at 30 fps. If, however, I activate both of them, the performance plummets. This has nothing to do with overloading my computer, as I can cut the complexity of each animation by a factor of 10 and the problem persists. My guess is the setIntervals are interfering with each other.

My question is whether it is safe to execute more than one setInterval calls. Thanks

Upvotes: 0

Views: 1382

Answers (5)

Lime
Lime

Reputation: 13569

I would advise using setTimeout it could avoid performance issuse.

Take a look at this question setTimeout or setInterval?

It does a great Job of explaining the difference between the two and why you should you generally use setTimeout.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816730

As the others say, you can have as much as possible. Nevertheless, you should have as few as necessary for good performance. Maybe you can find a way to use only one intervala for both animations.

There might be a problem though if you use global variables. This could have an influence on the animations (maybe even on the performance, depends on what you use them for).

Upvotes: 1

Duncan_m
Duncan_m

Reputation: 2546

Yes its safe to have multiple setIntervals running.. There's no underlying performance issue with using setIntervals.. profile your own code, you'll almost certainly find the problem there.

Upvotes: 0

Basic
Basic

Reputation: 26766

You can have many setIntervals() without issue but be aware that JS is fundamentally single-threaded (per-page). Multiple "Concurrent" threads are actually handled by jumping one thread about the code.

What this means is that timing won't be consistent - especially if one of the methods takes a considerable length of time to run.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359956

My question is whether it is safe to execute more than one setInterval calls

Short answer: yes, absolutely.

Upvotes: 0

Related Questions